如何在Javascript中重写基类构造函数 [英] How to override a base class constructor in Javascript

查看:460
本文介绍了如何在Javascript中重写基类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Udacity ES6培训有一个关于重写基类构造函数的问题.我有一个解决方案,但Udacity不允许我放弃它.

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.

任务是: 创建扩展Vehicle类的Bicycle子类. Bicycle子类应通过将车轮的默认值从4更改为2,将喇叭的默认值从哔哔"更改为鸣喇叭"来覆盖Vehicle的构造函数.

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
*/

我想出的解决方案是:

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:

您的Bicycles构造函数未设置颜色,车轮和喇叭的默认值

Your Bicycles constructor doesn't set default values for color, wheels, and horn

推荐答案

您不应使用

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

这篇关于如何在Javascript中重写基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆