Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Javascript中重写基类构造函数_Javascript_Constructor_Overriding_Es6 Class - Fatal编程技术网

如何在Javascript中重写基类构造函数

如何在Javascript中重写基类构造函数,javascript,constructor,overriding,es6-class,Javascript,Constructor,Overriding,Es6 Class,Udacity ES6培训有一个关于重写基类构造函数的问题。我有一个解决办法,但Udacity不让我得逞 任务是: 创建扩展Vehicle类的Bicycle子类。自行车子类应通过将车轮的默认值从4更改为2,并将喇叭从“嘟嘟嘟嘟”更改为“喇叭嘟嘟”来覆盖车辆的构造函数功能 class Vehicle { constructor(color = 'blue', wheels = 4, horn = 'beep beep') { this.color = color;

Udacity ES6培训有一个关于重写基类构造函数的问题。我有一个解决办法,但Udacity不让我得逞

任务是: 创建扩展Vehicle类的Bicycle子类。自行车子类应通过将车轮的默认值从4更改为2,并将喇叭从“嘟嘟嘟嘟”更改为“喇叭嘟嘟”来覆盖车辆的构造函数功能

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()
    }

}
但这还不够好,我不明白为什么会这样。我得到的反馈是:


您的自行车构造函数没有为颜色、车轮和喇叭设置默认值,您不应该使用

    this.wheels = 2
    this.horn = "honk honk" 
当已经在超级构造函数中重写这些时。
class车辆{
构造函数(颜色为“蓝色”,轮子为4,喇叭为“嘟嘟嘟嘟”){
这个颜色=颜色;
这个。轮子=轮子;
this.horn=horn;
}
honkHorn(){
console.log(this.horn);
}
}
二等车{
建造师(车轮=2,喇叭=honk-honk){
超级(未定义、车轮、喇叭);
}
honkHorn(){
super.honkHorn()
}
}
出租=新自行车;
作者:honkHorn()
然后,对于测试,我添加了:

const yourBike = new Bicycle(3, "tring tring")
尽管其他选项确实为问题中描述的测试用例提供了正确答案。通过添加这个额外的测试,我发现从super或this.wheels重写基类构造函数是不可能的(这是我的第一次尝试)


但是,Udacity不接受它……

我认为,即使在您的Bicycle类中,练习也希望您为每个构造函数参数设置默认值。类似这样:扩展上述答案(在你的自行车中)
constructor(wheels=2,horn='tring-tring')
你试过从Bycible构造函数中删除'this.wheels=2 this.horn=“honk-honk”`吗@埃德温
const yourBike = new Bicycle(3, "tring tring")