extends
语法
class ChildClass extends ParentClass { ... }
描述
示例
使用 extends
第一个例子是根据名为 Polygon
类创建一个名为 Square
的类。这个例子是从这个在线演示中提取出来的。
class Square extends Polygon {
constructor(length) {
// Here, it calls the parent class' constructor with lengths
// provided for the Polygon's width and height
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Leaving this out will cause a reference error.
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
}
使用 extends
与内置对象
扩展 null
可以像扩展普通类一样扩展 null
,但是新对象的原型将不会继承 Object.prototype
(en-US)。
class nullExtends extends null {
constructor() {}
}
Object.getPrototypeOf(nullExtends); // Function.prototype
Object.getPrototypeOf(nullExtends.prototype) // null
new nullExtends(); //ReferenceError: this is not defined
规范
Specification |
---|
ECMAScript Language Specification # sec-class-definitions |
浏览器兼容性
BCD tables only load in the browser