如何创建扩展函数的 class
How to create a class that extends a function
想象一下,您在 javascript 中创建了一个 class,就像往常一样
var Button = function( width ){
this.width;
}
var button = new button(13);
现在我想使用漂亮的 ES6 扩展它 classes
class ColorButton extends Button {
constructor( width, color ){
super(width);
this.color(color);
}
}
有没有办法让它起作用?
这似乎work as expected in Babel REPL:(示例代码已修改)
var Button = function( width ){
this.width = width;
console.log(this.width);
}
var superButton = new Button(13);
class ColorButton extends Button {
constructor( width, color ){
super(width);
this.color = color;
console.log(this.color);
}
}
var subButton = new ColorButton(25, "Red");
终于可以自己解决问题了。要使 javascript class 成为可扩展的函数,需要在原型中显式设置构造函数:
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!
想象一下,您在 javascript 中创建了一个 class,就像往常一样
var Button = function( width ){
this.width;
}
var button = new button(13);
现在我想使用漂亮的 ES6 扩展它 classes
class ColorButton extends Button {
constructor( width, color ){
super(width);
this.color(color);
}
}
有没有办法让它起作用?
这似乎work as expected in Babel REPL:(示例代码已修改)
var Button = function( width ){
this.width = width;
console.log(this.width);
}
var superButton = new Button(13);
class ColorButton extends Button {
constructor( width, color ){
super(width);
this.color = color;
console.log(this.color);
}
}
var subButton = new ColorButton(25, "Red");
终于可以自己解决问题了。要使 javascript class 成为可扩展的函数,需要在原型中显式设置构造函数:
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!