JavaScript/面向对象编程/练习
外观
< 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());