ES6 classes in the

Thanks to the new class feature in ES6, the weird behavior of new and function can finally be retired (although it doesn’t change at runtime). In any scenario, I recommend using ES6 syntax to define classes and returning function to its original function semantics. Let’s take a look at classes in ES6.

The class keyword was introduced in ES6, and all [[class]] related private attribute descriptions were removed from the standard. The concept of class was officially upgraded from attribute to language infrastructure, and class-based programming became the official programming paradigm of JavaScript.

Let’s take a look at the basic writing of the class:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width; }}Copy the code

The way classes are written is actually carried out by the stereotype runtime. Logically, JavaScript thinks of each class as a set of objects with a common stereotype, and the methods and properties defined in the class are written on top of the stereotype object.

In addition, and most importantly, classes provide inheritance capabilities. Let’s look at the following code.

class Animal { 
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.'); }}class Dog extends Animal {
  constructor(name) {
    super(name); // call the super class constructor and pass in the name parameter
  }

  speak() {
    console.log(this.name + ' barks.'); }}let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.
Copy the code