ES6 之 class 继承

// 通过 extends 关键字继承了 Point 类的所有属性和方法。但是由于没有部署任何代码,所以这两个类完全一样,等于复制了一个 Point 类
class Point {
}
class ColorPoint extends Point {
}

// constructor 方法和 toString 方法之中,都出现了 super 关键字,它在这里表示父类的构造函数,用来新建父类的 this 对象
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 方法中调用 super 方法,否则新建实例时会报错
class Point { /* ... */ }
class ColorPoint extends Point {
  constructor() { // 子类没有自己的 this 对象,而是继承父类的 this 对象,然后对其进行加工
  }
}
let cp = new ColorPoint(); // ReferenceError,如果不调用 super 方法,子类就得不到 this 对象
// ES5 的继承,实质是先创造子类的实例对象 this,然后再将父类的方法添加到 this上面(Parent.apply(this))。ES6 的继承机制完全不同,实质
// 是先创造父类的实例对象 this(所以必须先调用 super 方法),然后再用子类的构造函数修改 this。

// 如果子类没有定义 constructor 方法,这个方法会被默认添加
class ColorPoint extends Point {
}
class ColorPoint extends Point {  // 等同于(不管有没有显式定义,任何一个子类都有 constructor 方法)
  constructor(...args) {
    super(...args);
  }
}

// 在子类的构造函数中,只有调用 super 之后,才可以使用 this 关键字,否则会报错
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}
class ColorPoint extends Point {
  constructor(x, y, color) {
    this.color = color; // ReferenceError
    super(x, y);  // 子类实例的构建,是基于对父类实例加工,只有 super 方法才能返回父类实例
    this.color = color; // 正确
  }
}

// 生成子类实例(与 ES5 的行为完全一致)
let cp = new ColorPoint(25, 8, 'green');
cp instanceof ColorPoint // true
cp instanceof Point // true

// 父类的静态方法也会被子类继承
class A {
  static hello() {  // hello() 是 A 类的静态方法,B 继承 A,也继承了 A 的静态方法
    console.log('hello world');
  }
}
class B extends A {
}
B.hello()  // hello world

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值