// 编码挑战 #4
/*
- 重新创建挑战 #3,但这次使用 ES6 类:为 “CarCl ”类创建一个 “EVCl ”子类
- 将 “charge ”属性设为私有;
-
- 实现对该类的 “accelerate ”和 “chargeBattery ”方法进行链式处理的功能,同时更新 “CarCl ”类中的 “brake ”方法。他们进行了 “chining ”实验!
数据 CAR 1:“Rivian”,时速 120 公里,电量 23
祝您好运
*/
上一个挑战的代码如下
class CarCl {
constructor(make, speed) {
this.make = make;
this.speed = speed;
}
accelerate() {
this.speed += 10;
console.log(`${this.make} 速度为${this.speed}km/h`);
}
brake() {
this.speed -= 5;
console.log(`${this.make}速度为${this.speed}km/h`);
}
get speedUS() {
return this.speed / 1.6;
}
set speedUS(speed) {
this.speed = speed * 1.6;
}
}
const EV = function (make, speed, charge) {
this.make = make;
this.speed = speed;
this.charge = charge;
};
EV.prototype = Object.create(Car.prototype);
EV.prototype.chargeBattery = function (chargeTo) {
this.charge = chargeTo;
};
Car.prototype.accelerate = function () {
this.speed += 20;
this.charge--;
console.log(`BYD时速为${this.speed},电量剩余${this.charge}%`);
};
参考答案
1
class EVCl extends CarCl {
chargeBattery(chargeTo) {
this.charge = chargeTo;
}
accelerate() {
this.speed += 20;
this.charge--;
console.log(`BYD时速为${this.speed},电量剩余${this.charge}%`);
}
constructor(make, speed, charge) {
super(make, speed);
this.charge = charge;
}
}
const rivian = new EVCl('Rivian', 120, 23);
2
class EVCl extends CarCl {
#charge;
constructor(make, speed, charge) {
super(make, speed);
this.#charge = charge;
}
chargeBattery(chargeTo) {
this.#charge = chargeTo;
}
accelerate() {
this.speed += 20;
this.#charge--;
console.log(`BYD时速为${this.speed},电量剩余${this.#charge}%`);
}
}
const rivian = new EVCl('Rivian', 120, 23);
3
class CarCl {
constructor(make, speed) {
this.make = make;
this.speed = speed;
}
accelerate() {
this.speed += 10;
console.log(`${this.make} 速度为${this.speed}km/h`);
}
brake() {
this.speed -= 5;
console.log(`${this.make}速度为${this.speed}km/h`);
return this;
}
get speedUS() {
return this.speed / 1.6;
}
set speedUS(speed) {
this.speed = speed * 1.6;
}
}
class EVCl extends CarCl {
#charge;
constructor(make, speed, charge) {
super(make, speed);
this.#charge = charge;
}
chargeBattery(chargeTo) {
this.#charge = chargeTo;
return this;
}
accelerate() {
this.speed += 20;
this.#charge--;
console.log(`BYD时速为${this.speed},电量剩余${this.charge}%`);
return this;
}
}
const rivian = new EVCl('Rivian', 120, 23);
rivian.accelerate().accelerate().brake().chargeBattery(50);