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

ghhaqwfi  于 2023-05-05  发布在  Java
关注(0)|答案(3)|浏览(135)

Udacity ES6培训有一个关于重写基类构造函数的问题。我有一个解决方案,但Udacity不让我逃脱。
任务是:创建一个Bicycle子类,它扩展了Vehicle类。Bicycle子类应该覆盖Vehicle的构造函数,方法是将wheels的默认值从4改为2,将horn的默认值从'beep beep'改为'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);
    }
}

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

u3r8eeie

u3r8eeie1#

你不应该使用

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

yyyllmsg2#

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并不接受......

bwitn5fc

bwitn5fc3#

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(color,wheels = 2,horn = 'honk honk'){
        super(color,wheels,horn);
    }
}
//you need not want to call honkHorn() in the child it automatically calls from the parent.
const myVehicle = new Vehicle();
myVehicle.honkHorn(); // beep beep
const myBike = new Bicycle();
myBike.honkHorn(); // honk honk

相关问题