constructor メソッドは、class で作成されたオブジェクトの生成と初期化のための特殊なメソッドです。
構文
constructor([arguments]) { ... }
説明
"constructor" という名前の特殊なメソッドは、クラスに 1 個だけ持たせることができます。class に複数の constructor メソッドが含まれる場合、SyntaxError が投げられます。
constructor は、super キーワードを使用して親クラスの constructor を呼び出せます。
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;
}
}
既定のコンストラクタ
constructor メソッドを指定しなかった場合、既定のコンストラクタが使用されます。基本クラスの既定のコンストラクタは次のようになります:
constructor() {}
派生クラスの既定のコンストラクタは次のようになります:
constructor(...args) {
super(...args);
}
仕様
| 仕様 | 状況 | コメント |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) Constructor Method の定義 |
標準 | 初期定義。 |
| ECMAScript 2017 Draft (ECMA-262) Constructor Method の定義 |
ドラフト |
ブラウザ実装状況
| 機能 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| 基本サポート | 42.0 | 45 (45) | ? | ? | ? |
| 既定のコンストラクタ | ? | 45 (45) | ? | ? | ? |
| 機能 | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|---|
| 基本サポート | 未サポート | 42.0 | 45.0 (45) | ? | ? | ? | 42.0 |
| 既定のコンストラクタ | ? | ? | 45.0 (45) | ? | ? | ? | ? |