关于类与构造函数继承的小挑战

题目

/*

  1. 使用构造函数将电动汽车(称为 EV)作为 Car 的子 “类 ”来实现。除了品牌和当前速度外,EV 还具有当前电池电量(百分比)(“charge ”属性);
  2. 实现一个 “chargeBattery ”方法,该方法接收一个参数 “chargeTo”,并将电池电量设置为 “chargeTo”;
  3. 执行一个 “accelerate ”方法,将汽车速度提高 20%,电量减少 1%。然后记录如下信息 BYD时速 140 公里,电量 22%";
  4. 创建一个电动汽车对象,并尝试调用 “加速”、“刹车 ”和 “充电”(充电至 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();
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值