JavaScript参考手册
类 | Classes
extends
extends
关键字用于类声明或者类表达式中,以创建一个类,该类是另一个类的子类。
语法
class ChildClass extends ParentClass { ... }
描述
extends
关键字用来创建一个普通类或者内建对象的子类。
继承的.prototype
必须是一个Object
或者 null
。
示例
使用 extends
第一个例子是根据名为 Polygon
类创建一个名为Square
的类。这个例子是从这个在线demo中提取出来的。
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
与内置对象
这个示例继承了内置的Date
对象。这个例子是从这个在线演示中提取出来的。
class myDate extends Date {
constructor() {
super();
}
getFormattedDate() {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
}
}
扩展 null
可以像扩展普通类一样扩展null,但是新对象的原型将不会继承 Object.prototype。
class nullExtends extends null {
constructor() {}
}
Object.getPrototypeOf(nullExtends); // Function.prototype
Object.getPrototypeOf(nullExtends.prototype) // null
new nullExtends(); //ReferenceError: this is not defined
标准
Specification |
Status |
Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'extends' in that specification. |
Standard |
Initial definition. |
ECMAScript Latest Draft (ECMA-262)The definition of 'extends' in that specification. |
Living Standard |
|
浏览器兼容性
Feature |
Chrome |
Edge |
Firefox (Gecko) |
Internet Explorer |
Opera |
Safari |
---|---|---|---|---|---|---|
Basic support |
42.0 |
(Yes) |
45 (45) |
? |
? |
? |
Array subclassing |
43.0 |
(Yes) |
53 (53) |
? |
? |
? |
Feature |
Android |
Edge |
Firefox Mobile (Gecko) |
IE Mobile |
Opera Mobile |
Safari Mobile |
Chrome for Android |
---|---|---|---|---|---|---|---|
Basic support |
No support |
(Yes) |
45.0 (45) |
? |
? |
? |
42.0 |
Array subclassing |
No support |
(Yes) |
No support |
? |
? |
? |
43.0 |
类 | Classes相关
JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络