Udacity ES6培训有一个关于重写基类构造函数的问题。我有一个解决方案,但Udacity不允许我放弃它。
分配是:创建扩展Vehicle类的Bicycle子类。Bicycle子类应通过将车轮的默认值从4更改为2,将喇叭的默认值从“哔哔”更改为“鸣喇叭”来覆盖Vehicle的构造函数。
class Vehicle {
constructor(color = 'blue', wheels = 4, horn = 'beep beep') {
this.color = color;
this.wheels = wheels;
this.horn = horn;
}
honkHorn() {
console.log(this.horn);
}
}
// your code here
/* tests
const myVehicle = new Vehicle();
myVehicle.honkHorn(); // beep beep
const myBike = new Bicycle();
myBike.honkHorn(); // honk honk
*/
我想出的解决方案是:
class Bicycle extends Vehicle {
constructor(wheels, horn){
super(wheels, horn)
this.wheels = 2
this.horn = "honk honk"
}
honkHorn(){
super.honkHorn()
}
}
但这还不够好,我也不知道为什么。我得到的反馈是:
您的Bicycles构造函数未设置颜色,车轮和喇叭的默认值
你不应该使用
this.wheels = 2
this.horn = "honk honk"
当已经在超级构造函数中覆盖它们时。
class Vehicle {
constructor(color = 'blue', wheels = 4, horn = 'beep beep') {
this.color = color;
this.wheels = wheels;
this.horn = horn;
}
honkHorn() {
console.log(this.horn);
}
}
class Bicycle extends Vehicle {
constructor(wheels = 2, horn = 'honk honk') {
super(undefined, wheels, horn);
}
honkHorn() {
super.honkHorn()
}
}
let by = new Bicycle();
by.honkHorn();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句