javascript クラスの継承

クラスとクラスの継承について

作成日:2024-02-19, 更新日:2024-02-21

基本

class foobar { // 継承元にするクラス
  constructor() { // constructor()は必要っぽい
    this.consts();
    this.foo = 'a';
  }

  consts() {
    this.bar = 'b';
  }

  p() {
    console.log(this.foo + 'と' + this.bar);
  }
}

class foobar_custom extends foobar { // 「extends」で継承
  constructor() { // 変更無しなら修正不要
       super(); // 親のconstructor()を実行したいときは「super()」。他のメソッドは「super.xxx()」
  //   this.consts();
  //   this.foo = 'a';
  }

  consts() {
    this.bar = super(this.bar) + 'c'; // 「super()」で継承元で指定した変数を使う
  }

  p() {
    super.p(); // 「super.xxx()」で継承元のメソッドを使う
    console.log('追加でログ出力');
  }
}