extends キーワードは、class 宣言 や class 式内で、他のクラスの子としてクラスを作成するために使用します。
構文
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
仕様
| 仕様 | 状況 | コメント |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) extends の定義 |
標準 | 初期定義 |
| ECMAScript 2017 Draft (ECMA-262) extends の定義 |
ドラフト |
ブラウザ実装状況
| 機能 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| 基本サポート | 42.0 | 45 (45) | ? | ? | ? |
| 配列の派生クラス | 43.0 | 未サポート | ? | ? | ? |
| 機能 | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|
| 基本サポート | 未サポート | 45.0 (45) | ? | ? | ? | 42.0 |
| 配列の派生クラス | 未サポート | 未サポート | ? | ? | ? | 43.0 |