这篇翻译不完整。请帮忙从英语翻译这篇文章。
该特性处于 ECMAScript 6 规范草案中,目前的实现在未来可能会发生微调,请谨慎使用。
简介
class 根据 constructor 方法来创建和初始化对象。
语法
constructor([arguments]) { ... }
描述
一个 class 中只能有一个指定的 ”constructor“ (构造)方法。如果 class 定义的时候包含多个构造方法,程序将会抛出 SyntaxError 错误。
在构造方法中可以使用 super 关键字来调用父类的构造方法。
实例
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;
}
set area(value) {
this.area = value;
}
}
规格
| 规格 | 状态 | 注释 |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) Constructor Method |
Standard | Initial definition. |
浏览器兼容
| 特性 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 42.0 | Available in the Nightly channel only (since February 2015) | ? | ? | ? |
| 特性 | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | ? | 42.0 | Available in the Nightly channel only (since February 2015) | ? | ? | ? |
Firefox 注
- 默认构造函数目前尚未实现 (bug 1105463)