JavaScript中类的继承(ES6、class、extends、super)

       Class 可以通过extends关键字实现继承 这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。如下:

class Test{}

class ColorTest extends Test{}

       上面代码定义了一个ColorTest类,该类通过extends关键字,继承了Test类的所有属性和方法。但是由于没有部署任何代码,所以这两个类完全一样,等于复制了一个Test类。下面,我们在ColorTest内部加上代码:

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

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

       上面代码中,constructor方法和toString方法之中, 都出现了super关键字,它在这里表示父类的构造函数, 用来新建父类的this对象

       ES6 要求,子类的构造函数必须执行一次super函数

       子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。如果不调用super方法,子类就得不到this对象。

class Test { /* ... */ }

class ColorTest  extends Test {
  constructor() {
  }}

let res = new ColorTest(); // ReferenceError

       上面代码中,ColorTest 继承了父类Test ,但是它的构造函数没有调用super方法,导致新建实例时报错。

       需要注意的地方是,在子类的构造函数中,只有调用super之后,可以使用this关键字,否则会报错。这是因为子类实例的构建,是基于对父类实例加工,只有super方法才能返回父类实例

class Test {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }}

class ColorTest  extends Test{
  constructor(x, y, color) {
    this.color = color; // ReferenceError
    super(x, y);
    this.color = color; // 正确
  }}

       上面代码中,子类的constructor方法没有调用super之前,就使用this关键字,结果报错,而放在super方法之后结果正确。

发布了52 篇原创文章 · 获赞 181 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42881768/article/details/104719044