super の使用
CoddyのJavaScriptジャーニー「オブジェクト指向プログラミング」セクションの一部 — レッスン 37/56。
メソッドをオーバーライドするとき、super.methodName() を使用して親クラスの元のバージョンに引き続きアクセスできます。これにより、親の振る舞いを完全に置き換えるのではなく、拡張または変更することができます。
メソッドを持つ親クラスを作成します:
class Animal {
makeSound() {
return "Generic animal sound";
}
}親クラスを継承する子クラスを作成します:
class Dog extends Animal {
makeSound() {
// 最初に親のメソッドを呼び出します
const parentSound = super.makeSound();
// 次に、追加の機能で拡張します
return `${parentSound}, but also Woof!`;
}
}子クラスのインスタンスを作成します:
const myDog = new Dog();
console.log(myDog.makeSound());
// 出力: "Generic animal sound, but also Woof!"superキーワードを使用すると、子クラスで独自の機能を追加しながら、親クラスのメソッドを呼び出すことができます。
チャレンジ
calculateArea() メソッドを持つ Shape クラスと、それを継承する Rectangle クラスが与えられています。あなたのタスクは、super を使用して Rectangle クラスの calculateArea() メソッドをオーバーライドすることです。
Rectangle クラスの calculateArea() メソッドを完成させて、以下の処理を行ってください:
superを使用して親クラスのcalculateArea()メソッドを呼び出し、その結果を保存する- 長方形の実際の面積(
width × height)を計算する - 親クラスのメッセージと長方形の面積を組み合わせた文字列を返す。例:
Calculating area... Rectangle area: 50
チートシート
オーバーライドする際に、親クラスの元のメソッドにアクセスするには、super.methodName()を使用します。
class Animal {
makeSound() {
return "Generic animal sound";
}
}
class Dog extends Animal {
makeSound() {
const parentSound = super.makeSound();
return `${parentSound}, but also Woof!`;
}
}
const myDog = new Dog();
console.log(myDog.makeSound());
// 出力: "Generic animal sound, but also Woof!"これにより、親の機能を完全に置き換えるのではなく、拡張することができます。
自分で試してみよう
import { Shape } from './shapes.js';
import { Rectangle } from './shapes.js';
// テストコード - 変更しないでください
const rectangle = new Rectangle(5, 10);
console.log(rectangle.calculateArea()); // 期待される出力: "Calculating area... Rectangle area: 50"
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。