プロパティとメソッドの継承
CoddyのJavaScriptジャーニー「オブジェクト指向プログラミング」セクションの一部 — レッスン 28/56。
あるクラスが別のクラスを継承(extend)すると、親クラスからすべてのプロパティとメソッドを継承します。これは、子クラスが親クラスで定義されたすべてのものに自動的にアクセスできることを意味します。
プロパティとメソッドを持つ親クラスを作成しましょう:
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
eat() {
return `${this.name} is eating`;
}
sleep() {
return `${this.name} is sleeping`;
}
}次に、Animalを継承する子クラスを作成しましょう:
class Dog extends Animal {
constructor(name, age, breed) {
super(name, age);
this.breed = breed;
}
}Dogクラスのインスタンスを作成します:
const rex = new Dog("Rex", 3, "German Shepherd");さて、Dogクラスでeat()やsleep()を定義していなくても、これらのメソッドを使用することができます:
console.log(rex.eat()); // 出力: Rex is eating
console.log(rex.sleep()); // 出力: Rex is sleepingまた、継承されたすべてのプロパティにアクセスできます:
console.log(rex.name); // 出力: Rex
console.log(rex.age); // 出力: 3
console.log(rex.breed); // 出力: German Shepherdチャレンジ
Dessertを継承したCakeクラスを作成し、エクスポートしてください。Cakeは以下を持つ必要があります:
Dessertから継承されたすべてのプロパティとメソッド- 新しいプロパティ
flavor - 文字列“Added candles to ${this.name}!”を返す新しいメソッド
addCandles()
チートシート
子クラスは、extends キーワードを使用して、親クラスからすべてのプロパティとメソッドを継承します。
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
eat() {
return `${this.name} is eating`;
}
sleep() {
return `${this.name} is sleeping`;
}
}
class Dog extends Animal {
constructor(name, age, breed) {
super(name, age);
this.breed = breed;
}
}
const rex = new Dog("Rex", 3, "German Shepherd");
console.log(rex.eat()); // Rex is eating
console.log(rex.name); // Rex
console.log(rex.breed); // German Shepherd子クラスは、継承されたすべてのプロパティとメソッドを再定義することなくアクセスできます。
自分で試してみよう
import { Dessert } from './desserts.js';
import { Cake } from './desserts.js';
// テストコード - 変更しないでください
const myCake = new Cake("Birthday Cake", 300, "Chocolate");
console.log(myCake.describe()); // "Birthday Cake has 300 calories" と出力されるはずです
console.log(myCake.flavor); // "Chocolate" と出力されるはずです
console.log(myCake.addCandles()); // "Added candles to Birthday Cake!" と出力されるはずですこのレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。