これは Harmony(ECMAScript 6) 提案の一部であり、実験段階の技術です。
この技術の仕様は安定していません。ブラウザ互換性の一覧表を確認してください。またこれらの構文や動作は、仕様変更などにより、新しいバージョンのブラウザでは変更される可能性があるという点に注意してください。
constructor メソッドは、class で作成されたオブジェクトの生成と初期化のための特殊なメソッドです。
構文
constructor([arguments]) { ... }
説明
"constructor" という名前の特殊なメソッドは、クラスに 1 個だけ持たせることができます。class に複数の constructor メソッドが含まれる場合、SyntaxError が投げられます。
constructor は、super キーワードを使用して親クラスの constructor を呼び出せます。
例
このコードスニペットは、classes sample (ライブデモ) から転載しています。
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 6 (ECMA-262) The definition of 'Constructor Method' in that specification. |
勧告候補 | Initial definition. |
ブラウザ実装状況
| 機能 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| 基本サポート | 42.0 | Nightly build | ? | ? | ? |
| 機能 | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| 基本サポート | ? | 42.0 | Nightly build | ? | ? | ? |
Firefox 固有のメモ
- デフォルトコンストラクタはまだ実装されていません (バグ 1105463)。