【发布时间】:2022-01-09 16:13:17
【问题描述】:
我在一门课程中学习继承,但是我在 MDN 上找到了 super 关键字,我开始实现它,它有点工作,它将返回父类中的两个属性,但附加属性 i尝试在子类中实现总是返回未定义,我怎样才能以正确的方式添加属性,因为我开始理解它可能是错误的,超级将 this 关键字应用于父类。这是我的代码...
class Car {
constructor(speed, make){
this.speed = speed,
this.make = make
}
get speed() {
return this._speed / 1.6;
}
set speed(mov){
this._speed = mov * 1.6
}
accel(){
console.log(this.speed += 5);
}
}
const chevy = new Car(120, 'chevy');
//challenge 3
class Ev extends Car{
constructor(speed,make,bat){
super(speed,make)
this.bat
}
billy(){
console.log('hi');
}
chargeBat(charge){
this.bat = charge;
return `ur battery is charging to ${charge}`;
}
cel(){
this.speed += 20;
this.bat - 1;
return `your car is going ${this.speed} and battery is ${this.bat}`
}
}
// Ev.protype = Object.create(Car.prototype);
const prius = new Ev(35,'prius',99);
// console.log(prius.chargeBat());
// console.log(prius.cel())
console.log(prius.bat);
console.log(prius.speed)
【问题讨论】:
-
在构造函数中,你不会对
this.bat或bat做任何事情。你正在寻找this.bat = bat;,就像你在基类中做的那样。 -
您没有设置 bat 值。在 Ev ctor 中尝试
this.bat = bat; -
同样,您可能指的是
this.bat -= 1;,而不是cel方法中的this.bat - 1;。 -
另外,不要使用逗号运算符来分配多个属性。
this.speed = speed; this.make = make;,而不是this.speed = speed, this.make = make;。使用JSHint 等工具立即发现代码问题。
标签: javascript inheritance super