constructor
是一种用于创建和初始化class
创建的对象的特殊方法。
constructor([arguments]) { ... }
在一个类中只能有一个名为 “constructor” 的特殊方法。 一个类中出现多次构造函数 (constructor)
方法将会抛出一个 SyntaxError
错误。
在一个构造方法中可以使用super
关键字来调用一个父类的构造方法。
如果没有显式指定构造方法,则会添加默认的 constructor 方法。
如果不指定一个构造函数(constructor)方法, 则使用一个默认的构造函数(constructor)。
constructor
方法class Square extends Polygon {
constructor(length) {
// 在这里, 它调用了父类的构造函数, 并将 lengths 提供给 Polygon 的"width"和"height"
super(length, length);
// 注意: 在派生类中, 必须先调用 super() 才能使用 "this"。
// 忽略这个,将会导致一个引用错误。
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
// 注意:不可使用 this.area = value
// 否则会导致循环call setter方法导致爆栈
this._area = value;
}
}
看看这个代码片段
class Polygon {
constructor() {
this.name = "Polygon";
}
}
class Square extends Polygon {
constructor() {
super();
}
}
class Rectangle {}
Object.setPrototypeOf(Square.prototype, Rectangle.prototype);
console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false
console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true
let newInstance = new Square();
console.log(newInstance.name); //Polygon
这里,Square类的原型被改变,但是在正在创建一个新的正方形实例时,仍然调用前一个基类Polygon的构造函数。
如前所述,如果不指定构造方法,则使用默认构造函数。对于基类,默认构造函数是:
constructor() {}
对于派生类,默认构造函数是:
constructor(...args) {
super(...args);
}
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) Constructor Method |
Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262) Constructor Method |
Draft |
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
constructor | Chrome
Full support
49
| Edge Full support 13 | Firefox Full support 45 | IE No support No | Opera Full support 36 | Safari Full support 9 | WebView Android ? | Chrome Android Full support Yes | Edge Mobile Full support 13 | Firefox Android Full support 45 | Opera Android ? | Safari iOS Full support 9 | Samsung Internet Android Full support Yes | nodejs
Full support
6.0.0
|