Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ チャレンジ:extendsとsuper()を使ったクラス継承の実装 | JavaScriptクラスと継承の習得
JavaScriptロジックとインタラクション

bookチャレンジ:extendsとsuper()を使ったクラス継承の実装

メニューを表示するにはスワイプしてください

課題

さまざまな種類の車両を管理する運輸管理システムを開発しています。各車両には make(メーカー)、model(モデル)、year(年式)が設定されています。電気自動車の場合は、さらに batteryCapacity(バッテリー容量)も管理する必要があります。継承を利用して、一般的な Vehicle クラスから電気自動車専用のクラスを拡張します。

  1. ElectricVehicle クラスを継承する Vehicle クラスを作成する;
  2. ElectricVehicle のコンストラクタは makemodelyearbatteryCapacity を受け取る;
  3. 親クラスの初期化には super() を使い、makemodelyear を初期化する;
  4. getDetailsElectricVehicle メソッドを追加し、VehiclegetDetails メソッドをオーバーライドする。このメソッドでは super.getDetails() を呼び出し、batteryCapacity の情報を追加する。フォーマットは次の通り:"{make} {model} ({year}) with a battery capacity of {batteryCapacity} kWh."
12345678910111213141516171819202122232425262728293031
class Vehicle { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; } getDetails() { return `${this.make} ${this.model} (${this.year})`; } } class ElectricVehicle _____ _____ { _____(make, model, year, _____) { _____(_____, _____, _____); this.batteryCapacity = batteryCapacity; } _____() { return `${super._____} with a battery capacity of ${ _____._____ } kWh.`; } } // Testing const vehicle = new Vehicle('Toyota', 'Camry', 2020); console.log(vehicle.getDetails()); // Expected: Toyota Camry (2020) const electricVehicle = new ElectricVehicle('Tesla', 'Model 3', 2021, 75); console.log(electricVehicle.getDetails()); // Expected: Tesla Model 3 (2021) with a battery capacity of 75 kWh.
copy
  • ElectricVehicle を継承するクラス Vehicle の定義;
  • ElectricVehicle のコンストラクタでは、batteryCapacitymakemodel の後に year パラメータを追加;
  • 親クラスのコンストラクタ呼び出しには super(make, model, year) を使用し、makemodelyear を初期化;
  • batteryCapacityElectricVehicle のプロパティとして設定;
  • getDetailsElectricVehicle メソッドを定義し、VehiclegetDetails メソッドをオーバーライド;
  • getDetails 内で super.getDetails() を利用して親クラスの詳細を取得し、バッテリー容量の情報を返却文字列に追加。
12345678910111213141516171819202122232425262728293031
class Vehicle { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; } getDetails() { return `${this.make} ${this.model} (${this.year})`; } } class ElectricVehicle extends Vehicle { constructor(make, model, year, batteryCapacity) { super(make, model, year); this.batteryCapacity = batteryCapacity; } getDetails() { return `${super.getDetails()} with a battery capacity of ${ this.batteryCapacity } kWh.`; } } // Testing const vehicle = new Vehicle('Toyota', 'Camry', 2020); console.log(vehicle.getDetails()); // Output: Toyota Camry (2020) const electricVehicle = new ElectricVehicle('Tesla', 'Model 3', 2021, 75); console.log(electricVehicle.getDetails()); // Output: Tesla Model 3 (2021) with a battery capacity of 75 kWh.
copy

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  15

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  15
some-alt