計算機科学のブログ

クラス クラスの拡張 extendsキーワード、superキーワード

入門JavaScriptプログラミング (JD Isaacks(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT6(クラス)、LESSON 28(クラスの拡張)、28.5(練習問題)、Q28-1の解答を求めてみる。

コード

class Car {
    constructor() {
        this.gas = 50;
        this.milage = 0;
    }
    hasGas() {
        return this.gas > 0;
    }
    drive() {
        if (this.hasGas()) {
            this.milage++;
            this.gas--;
        }
    }
}
class ExtendedCar extends Car {
    constructor() {
        super();
    }
    fuel() {
        this.gas = 50;
    }
    drive(miles = 1) {
        for (let index = 0; index < miles; index++) {
            if (!this.hasGas()) {
                this.fuel();
            }
            super.drive();
        }
    }
}

let car = new ExtendedCar();

for (let miles = 1; miles <= 50; miles++) {
    car.drive(miles);
    console.log(`miles: ${miles}, gas: ${car.gas}`);
}

入出力結果(Terminal、Zsh)

% node sample.js
miles: 1, gas: 49
miles: 2, gas: 47
miles: 3, gas: 44
miles: 4, gas: 40
miles: 5, gas: 35
miles: 6, gas: 29
miles: 7, gas: 22
miles: 8, gas: 14
miles: 9, gas: 5
miles: 10, gas: 45
miles: 11, gas: 34
miles: 12, gas: 22
miles: 13, gas: 9
miles: 14, gas: 45
miles: 15, gas: 30
miles: 16, gas: 14
miles: 17, gas: 47
miles: 18, gas: 29
miles: 19, gas: 10
miles: 20, gas: 40
miles: 21, gas: 19
miles: 22, gas: 47
miles: 23, gas: 24
miles: 24, gas: 0
miles: 25, gas: 25
miles: 26, gas: 49
miles: 27, gas: 22
miles: 28, gas: 44
miles: 29, gas: 15
miles: 30, gas: 35
miles: 31, gas: 4
miles: 32, gas: 22
miles: 33, gas: 39
miles: 34, gas: 5
miles: 35, gas: 20
miles: 36, gas: 34
miles: 37, gas: 47
miles: 38, gas: 9
miles: 39, gas: 20
miles: 40, gas: 30
miles: 41, gas: 39
miles: 42, gas: 47
miles: 43, gas: 4
miles: 44, gas: 10
miles: 45, gas: 15
miles: 46, gas: 19
miles: 47, gas: 22
miles: 48, gas: 24
miles: 49, gas: 25
miles: 50, gas: 25
%