关键字创建一个基于原型继承的新类(译者注:ES2015新加入的class关键字是语法糖,本质还是函数)
你也可以使用类表达式class expression定义类。但是不同于类表达式,类声明(类语句)不允许再次声明已经存在的类,否则将会抛出一个类型错误。
Syntax 语法
class name [extends] {
// class body
}
Description 描述
和class表达式一样,class声明体在严格模式(strict mode)下运行。构造函数(constructor)是可选的。
Class声明不可以提升(这点和函数声明不一样)。
Examples 例子
一个类声明的例子
在下面的例子,定义了一个名为Polygon的类,然后定义了一个继承于Polygon的类 Square。注意到在构造器使用的 super(),super()只能在构造器中使用,super函数一定要在this可以使用之前调用。
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
}
class Square extends Polygon {
constructor(length) {
super(length, length);
this.name = 'Square';
}
}
重复定义类
重复定义类会引起类型错误.
class Foo {};
class Foo {}; // Uncaught TypeError: Identifier 'Foo' has already been declared
由于类声明不会被提升,所以,在定义之前引用类会出错.
var Foo = class {};
class Foo {}; // Uncaught TypeError: Identifier 'Foo' has already been declared
Specifications 规范
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) Class definitions |
Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) Class definitions |
Living Standard |
Browser compatibility 浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 42.0 | Nightly build | ? | ? | ? |
| Array subclassing | 43.0 | 未实现 | ? | ? | ? |
| Feature | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|---|
| Basic support | 未实现 | 42.0 | Nightly build | ? | ? | ? | 42.0 |
| Array subclassing | 未实现 | 43.0 | 未实现 | ? | ? | ? | 43.0 |