instructions

  • Suitable for es6 beginners
  • Understand the use of class

Extends inheritance

  • Classes can be inherited through the extends keyword, which is much cleaner and more convenient than ES5’s inheritance through modified prototype chains.
class Point{}class ColorPoint extends Point{}Copy the code

The above code defines a ColorPoint class that inherits all the properties and methods of the Point class through the extends keyword. But since no code is deployed, the two classes are exactly the same, duplicating a Point class. Next, we add code inside ColorPoint.

Super calls the parent class constructor

class ColorPoint extends Point {
  constructor(x, y, color) {
    super(x, y); // Call parent constructor(x, y)
    this.color = color;
  }

  toString() {
    return this.color + ' ' + super.toString(); // Call the parent toString()}}Copy the code
  • superTo call the parent class’s constructor

The subclass does not define constructor and is added by default

class ColorPoint extends Point {}/ / is equivalent to
class ColorPoint extends Point {
  constructor(... args) {super(...args);
  }
}
Copy the code

Use super properly

Super is called as a function

  • In the first case,superKeyword is called as a function. In ES6, the constructor of a subclass must execute super (Remember that we can omit constructor and super and the function will be added automatically, see the case at 👆)
class A {}

class B extends A {
  constructor() {
    super();
  }
}
Copy the code

Note that super although represents the parent class constructor, but returns the instance of the subclass B, namely the inside of the super this refers to B, so super () is equivalent to Amy polumbo rototype here. The constructor. Call (this).

class A {
  constructor() {
    console.log(new.target.name); }}class B extends A {
  constructor() {
    super();
  }
}
new A() // A
new B() // B
Copy the code

In the above code, new.target points to the function currently executing. As you can see, when super() executes, it points to the constructor of subclass B, not the constructor of superclass A. That is, the this inside super() refers to B.

Super is used as an object

  • In the second case,superAs an object, in a normal method, a prototype object that points to the parent class; In static methods, point to the parent class.
class A {
  p() {
    return 2; }}class B extends A {
  constructor() {
    super(a);console.log(super.p()); / / 2}}let b = new B();
Copy the code