题目
/*
- 使用构造函数将电动汽车(称为 EV)作为 Car 的子 “类 ”来实现。除了品牌和当前速度外,EV 还具有当前电池电量(百分比)(“charge ”属性);
- 实现一个 “chargeBattery ”方法,该方法接收一个参数 “chargeTo”,并将电池电量设置为 “chargeTo”;
- 执行一个 “accelerate ”方法,将汽车速度提高 20%,电量减少 1%。然后记录如下信息 BYD时速 140 公里,电量 22%";
- 创建一个电动汽车对象,并尝试调用 “加速”、“刹车 ”和 “充电”(充电至 90%)。注意 “加速 ”时会发生什么!提示:复习多态性的定义 😉
数据车 1:“BYD”,时速 120 公里,电量 23
祝你好运
*/
1
function Car(make, speed) {
this.make = make;
this.speed = speed;
}
const EV = function (make, speed, charge) {
this.make = make;
this.speed = speed;
this.charge = charge;
};
2
function Car(make, speed) {
this.make = make;
this.speed = speed;
}
const EV = function (make, speed, charge) {
this.make = make;
this.speed = speed;
this.charge = charge;
};
EV.prototype.chargeBattery = function (chargeTo) {
this.charge = chargeTo;
};
3
function Car(make, speed) {
this.make = make;
this.speed = speed;
}
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}`);
};
const BYD = new EV('BYD', 120, 23);
BYD.accelerate();
4
//刹车
Car.prototype.brake = function () {
this.speed -= 5;
console.log(`${this.make}的速度已经达到${this.speed}`);
};
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}%`);
};
const BYD = new EV('BYD', 120, 23);
BYD.accelerate();
BYD.brake();
BYD.accelerate();