extends
extends
キーワードはクラス宣言やクラス式の中で、他のクラスの子であるクラスを生成するために使用します。
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
キーワードは、独自のクラスや組込みオブジェクトをサブクラス化するために使用することができます。
例
extends の使用
最初の例では、 Square
と呼ばれるクラスを Polygon
と呼ばれるクラスから作成します。この例は、ライブデモ (ソース) から転載しています。
class Square extends Polygon {
constructor(length) {
// ここでは、親クラスのコンストラクターを呼び出し、
// Polygon の幅と高さの寸法を渡します。
super(length, length);
// 注: 派生クラスでは、 'this' を使う前に super() を
// 呼び出さなくてはなりません。さもないと参照エラーになります。
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
}
組込みオブジェクトでの extends の使用
この例では、組込みの Date
オブジェクトを拡張します。この例は、ライブデモ (ソース) から転載しています。
class myDate extends Date {
getFormattedDate() {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
}
}
仕様書
ブラウザーの互換性
BCD tables only load in the browser