JavaScript

extends

 編集:2022.08.11 by T.A.

extends キーワードはクラス宣言クラス式の中で、他のクラスの子であるクラスを生成するために使用します。

class ChildClass extends ParentClass { }
ChildClass 子クラスの名前
ParentClass 親クラスの名前
解説

extends キーワードは、独自のクラスや組込みオブジェクトをサブ クラス化するために使用することができます。

拡張したものの .prototype は、Object か null である必要があります。

最初の例では、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();
  }
}

テスト