如何创建扩展函数的类

时间:2015-04-29 18:28:51

标签: javascript ecmascript-6

想象一下,你在javascript中创建了一个像往常一样的类

var Button = function( width ){
    this.width;
}
var button = new button(13);

现在我想用漂亮的ES6类扩展它

class ColorButton extends Button {
    constructor( width, color ){
        super(width);
        this.color(color);
    }
}

有没有办法让它发挥作用?

1 个答案:

答案 0 :(得分:1)

最后,我可以自己解决问题。为了使javascript类成为可扩展的函数,需要在原型中显式设置构造函数:

var Button = function( width ){
    this.width = width;
}

// This is the key part
Button.prototype = {
  constructor: Button
}

class ColorButton extends Button {};
var subButton = new ColorButton(25);

console.log( subButton.width ); // 25, it works!
相关问题