如何覆盖 Javascript 中的基本 class 构造函数

How to override a base class constructor in Javascript

Udacity ES6 培训有一个关于覆盖基础 class 构造函数的问题。我有一个解决方案,但 Udacity 不允许我逃脱。

作业是: 创建一个 Bicycle subclass 来扩展 Vehicle class。 Bicycle subclass 应该通过将车轮的默认值从 4 更改为 2 并将喇叭的默认值从 'beep beep' 更改为 'honk honk'.

来覆盖 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();

class Bicycle extends Vehicle {
    constructor(wheels =2, horn= "honk honk"){
        super(undefined, wheels, horn)
    }

    honkHorn(){
        super.honkHorn()
    }

}

然后为了测试我添加了:

const yourBike = new Bicycle(3, "tring tring")

尽管其他选项确实为问题中描述的测试用例提供了正确答案。通过添加这个额外的测试,我发现 super 和 this.wheels 都不可能覆盖基础 class 构造函数(这是我的第一次尝试)。

然而优达学城不接受......