ES6学习(八):Class的继承

1. 简介

Class 可以通过extends关键字实现继承,让子类继承父类的属性和方法。 除了私有属性,父类的所有属性和方法,都会被子类继承,其中包括静态方法。

class Point {
          
   
  constructor(x, y) {
          
   
    this.x = x;
    this.y = y;
  }
  toString() {
          
   
    return ( + this.x + ,  + this.y + );
  }
}

class ColorPoint extends Point {
          
   
  constructor(x, y, color) {
          
   
    super(x, y); // 调用父类的constructor(x, y)
    this.color = color;
  }

  toString() {
          
   
    return this.color +   + super.toString(); // 调用父类的toString()
  }
}

上面示例中,constructor()方法和toString()方法内部,都出现了super关键字。super在这里表示父类的构造函数,用来新建一个父类的实例对象。 ES6 规定,子类必须在constructor()方法中调用super(),否则就会报错。所以父类的构造函数必定会先运行一次

2. Object.getPrototypeOf()

Object.getPrototypeOf()方法可以用来从子类上获取父类。

class Point {
          
    /*...*/ }
class ColorPoint extends Point {
          
    /*...*/ }
Object.getPrototypeOf(ColorPoint) === Point
// true

因此,可以使用这个方法判断,一个类是否继承了另一个类。

3. super 关键字

super这个关键字,既可以当作函数使用,也可以当作对象使用。在这两种情况下,它的用法完全不同。

第一种情况,super作为函数调用时,代表父类的构造函数。ES6 要求,子类的构造函数必须执行一次super函数。 作为函数时,super()只能用在子类的构造函数之中,用在其他地方就会报错。

第二种情况,super作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。 由于super指向父类的原型对象,所以定义在父类实例上的方法或属性,是无法通过super调用的。

class A {
          
   
  constructor() {
          
   
    this.p = 2;
  }
}
A.prototype.x = 1;

class B extends A {
          
   
  constructor() {
          
   
    super();
    console.log(super.x) // 1
  }
  get m() {
          
   
    return super.p;
  }
}

let b = new B();
b.m // undefined
经验分享 程序员 微信小程序 职场和发展