constructor メソッドは、class で作成されたオブジェクトの生成と初期化のための特殊なメソッドです。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
構文
constructor([arguments]) { ... }
説明
「constructor」という名前の特殊なメソッドは、クラスに 1 個だけ持たせることができます。class に複数の constructor メソッドが含まれる場合、SyntaxError が投げられます。
constructor は、super キーワードを使用して親クラスの constructor を呼び出せます。
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;
}
}
他の例
このコードスニペットを見てください。
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 クラスのプロトタイプは変更されていますが、square の新しいインスタンスが作成される時に前の基底クラスの Polygon が呼び出されています。
既定のコンストラクタ
constructor メソッドを指定しなかった場合、既定のコンストラクタが使用されます。基本クラスの既定のコンストラクタは次のようになります:
constructor() {}
派生クラスの既定のコンストラクタは次のようになります:
constructor(...args) {
super(...args);
}
仕様
| 仕様 | 状況 | コメント |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) Constructor Method の定義 |
標準 | 初期定義。 |
| ECMAScript (ECMA-262) Constructor Method の定義 |
現行の標準 |
ブラウザー実装状況
| デスクトップ | モバイル | サーバー | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
constructor | Chrome
完全対応
49
| Edge 完全対応 13 | Firefox 完全対応 45 | IE 未対応 なし | Opera
完全対応
36
| Safari 完全対応 9 | WebView Android
完全対応
49
| Chrome Android
完全対応
49
| Firefox Android 完全対応 45 | Opera Android
完全対応
36
| Safari iOS 完全対応 9 | Samsung Internet Android 完全対応 5.0 | nodejs
完全対応
6.0.0
|
凡例
- 完全対応
- 完全対応
- 未対応
- 未対応
- 実装ノートを参照してください。
- 実装ノートを参照してください。
- ユーザーが明示的にこの機能を有効にしなければなりません。
- ユーザーが明示的にこの機能を有効にしなければなりません。