JavaScript面向对象小挑战

// 编码挑战 #4

/*

  1. 重新创建挑战 #3,但这次使用 ES6 类:为 “CarCl ”类创建一个 “EVCl ”子类
  2. 将 “charge ”属性设为私有;
    1. 实现对该类的 “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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值