跳至內容

JavaScript/面向物件程式設計/練習

來自維基百科,面向開放世界的開放書籍

主題:面向物件程式設計 - 2




1. 建立一個“Car”類,具有(至少)兩個屬性。

點選檢視解決方案
"use strict";

class Car {

  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }
  show() {
    return "My car is a " + this.brand + " " + this.model;
  }
}

const myCityCar = new Car("Fiat", "Cinquecento");
const mySportsCar = new Car("Maserati", "MC20");

alert(myCityCar.show());
alert(mySportsCar.show());

2. 建立一個“Truck”類,它是上面“Car”類的子類。它具有一個附加屬性“maxLoad”。

點選檢視解決方案
"use strict";

class Car { // same as above
  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }
  show() {
    return "My car is a " + this.brand + " " + this.model;
  }
}
class Truck extends Car {
  constructor(brand, model, maxLoad) {
    super(brand, model);
    this.maxLoad = maxLoad;
  }
  show() {
    return "My truck is a " + this.brand + " " + this.model + 
           ". It transports up to " + this.maxLoad;
  }
}

const myTruck = new Truck("Caterpillar", "D350D", "25 tonne");

alert(myTruck.show());
華夏公益教科書