ES6 class 的 extends 继承和 ES5 原型继承有什么联系?
请说明 ES6 class 和 extends 关键字的本质,以及与 ES5 原型继承的关系。
回答
苦行僧
本质:ES6 class 是 ES5 原型继承的语法糖,底层仍然是原型链。
对比:
ES6 写法:
class Parent { constructor(name) { this.name = name; } }
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
ES5 等价实现:
function Parent(name) { this.name = name; }
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
区别:
- ES6 class 必须用 new 调用(内部有
[[IsClassConstructor]]检查) - class 不会提升(有 TDZ)
- class 方法不可枚举(
enumerable: false),ES5 原型方法可枚举 - extends 内置类(如 Array)时,子类能继承内置类实例的内部属性(原生支持
Species) - super 用于调用父类构造函数和方法,实质是
Parent.call(this)+Parent.prototype.method.call(this)