问题
The Udacity ES6 training has a question about overriding a base class constructor. I've got a solution but Udacity doesn't let me get away with it.
The assignment is: Create a Bicycle subclass that extends the Vehicle class. The Bicycle subclass should override Vehicle's constructor function by changing the default values for wheels from 4 to 2 and horn from 'beep beep' to '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
*/
The solution that I come up with is:
class Bicycle extends Vehicle {
constructor(wheels, horn){
super(wheels, horn)
this.wheels = 2
this.horn = "honk honk"
}
honkHorn(){
super.honkHorn()
}
}
But that is not good enough And I do not understand why that is. The feedback I got is:
Your Bicycles constructor doesn't set default values for color, wheels, and horn
回答1:
you should not be using
this.wheels = 2
this.horn = "honk honk"
when already overriding these in super constructor.
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();
回答2:
class Bicycle extends Vehicle {
constructor(wheels =2, horn= "honk honk"){
super(undefined, wheels, horn)
}
honkHorn(){
super.honkHorn()
}
}
then for the test I added:
const yourBike = new Bicycle(3, "tring tring")
Although other options did provide the right answers for the test cases described in the question. By adding this extra test I found out that overriding a base class constructor is not possible from super nor from this.wheels (as was my first attempt).
However Udacity does not accept it......
来源:https://stackoverflow.com/questions/55760091/how-to-override-a-base-class-constructor-in-javascript