LoginSignup
0
1

【JavaScript】super

Last updated at Posted at 2023-05-24

super

親クラスのメソッドやコンストラクタを呼び出すためのキーワード

▼ コンストラクタ内で親クラスのコンストラクタを呼び出す場合:

.js
class Child extends Parent {
  constructor(gender) {
    super(...arguments); // ここで親クラスのコンストラクタを呼び出す
    // このクラスに新たに値を追加することが可能 
    this.gender = gender;
  }
}

▼ メソッド内で親クラスの同名のメソッドを呼び出す場合

.js
class Child extends Parent {
  someMethod() {
    super.someMethod(); // 親クラスの同名のメソッドを呼び出す
    // その他の処理...
  }
}

・superは、継承されたクラスのコンストラクタやメソッドを呼び出す際に必要なもの
 superを使用することで、親クラスの処理を引き継ぎつつ、子クラスで追加の処理を行うことができる

・superは、親クラスのメソッド呼び出し以外にも、super()のように親クラスのコンストラクタ呼び出しを行うためにも使用される

Example

.js
class Vehicle {
  constructor(brand) {
    this.brand = brand;
  }

  honk() {
    console.log('Beep beep!');
  }
}

class Car extends Vehicle {
  constructor(brand, model) {
    super(brand); // スーパークラスのコンストラクタを呼び出す
    this.model = model;
  }

  honk() {
    super.honk(); // スーパークラスのメソッドを呼び出す
    console.log(`I'm a ${this.brand} ${this.model}!`);
  }
}

const myCar = new Car('Toyota', 'Corolla');
myCar.honk(); // Beep beep! \n I'm a Toyota Corolla!

Vehicleというスーパークラスを定義し、CarというクラスがVehicleを継承
Carクラスのコンストラクタ内でsuper(brand)を呼び出すことで、
Vehicleクラスのコンストラクタを実行
また、Carクラス内でhonkメソッドをオーバーライドし、super.honk()を使用してスーパークラスのhonkメソッドを呼び出している

参考資料

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1