想象一下,你在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);
}
}
有没有办法让它发挥作用?
答案 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!