跳至内容

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());
华夏公益教科书