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

时间:2019-04-19 10:02:23

标签: javascript constructor override es6-class

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构造函数未设置颜色,车轮和喇叭的默认值

2 个答案:

答案 0 :(得分:1)

您不应该使用

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

答案 1 :(得分:0)

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覆盖基类构造函数(这是我的第一次尝试)。

但是Udacity不接受它……