extends は、該当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.
構文
class ChildClass extends ParentClass { ... }
説明
extends キーワードは、カスタムクラスやビルトインオブジェクトをサブクラス化するために使用できます。
.prototype 拡張は、Object か null の必要があります。
例
extends の使用
最初の例は、Polygon と呼ばれるクラスから Square と呼ばれるクラスを作成します。この例は、ライブデモ (ソース) から転載しています。
class Square extends Polygon {
constructor(length) {
// ここでは、親クラスのコンストラクタを呼び出し、
// Polygon の幅と高さの length を与えます。
super(length, length);
// Note: 引き出されたクラスでは、'this' を使う前に
// super() を呼び出さなくてはなりません。 こうしなければ、参照エラーになります。
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value;
}
}
ビルトインオブジェクトでの extends の使用
この例は、組み込みの Date オブジェクトを拡張します。この例は、ライブデモ (ソース) から転載しています。
class myDate extends Date {
constructor() {|
super();
}
getFormattedDate() {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
}
}
null の拡張
プロトタイプオブジェクトが Object.prototype を継承しない点を除いて、null の継承は通常のクラスのように動作します。
class nullExtends extends null {
constructor() {}
}
Object.getPrototypeOf(nullExtends); // Function.prototype
Object.getPrototypeOf(nullExtends.prototype) // null
new nullExtends(); //ReferenceError: this is not defined
仕様
| 仕様 | 状況 | コメント |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) extends の定義 |
標準 | 初期定義 |
| ECMAScript Latest Draft (ECMA-262) extends の定義 |
ドラフト |
ブラウザ実装状況
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
| デスクトップ | モバイル | サーバー | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
extends | Chrome
完全対応
49
| Edge 完全対応 13 | Firefox 完全対応 45 | IE 未対応 なし | Opera 完全対応 36 | Safari 完全対応 9 | WebView Android
完全対応
49
| Chrome Android
完全対応
49
| Firefox Android 完全対応 45 | Opera Android ? | Safari iOS 完全対応 9 | Samsung Internet Android 完全対応 あり | nodejs
完全対応
6.0.0
|
凡例
- 完全対応
- 完全対応
- 未対応
- 未対応
- 実装状況不明
- 実装状況不明
- 実装ノートを参照してください。
- 実装ノートを参照してください。
- ユーザーが明示的にこの機能を有効にしなければなりません。
- ユーザーが明示的にこの機能を有効にしなければなりません。