Veg*_*gar 7 javascript ecmascript-6 phaser-framework
据我所知,this在super( )调用之前,构造函数内部不可用.
但是,在引用实例方法时,我们需要为方法添加前缀this.那么如何将实例方法传递给super( )?
例如,在Phaser框架中,有一个Button类.构造函数对click事件进行回调:
构造函数
new Button(game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)callback - 按下此按钮时调用的函数.
callbackContext - 将调用回调的上下文(通常为"this").
我想要我自己的按钮类,我定义如下:
class MyButton extends Phaser.Button {
constructor(game) {
super(game, game.world.centerX, game.world.centerY, 'buttonImage');
}
clickHandler(button, pointer) {
//handle the clicking
}
}
Run Code Online (Sandbox Code Playgroud)
所以,我怎么会传递clickHandler到super?
this.clickHandler给出错误[Build Error] 'this' is not allowed before super() while parsing file: ....并传递clickHandler给我一个运行时错误Uncaught ReferenceError: clickHandler is not defined.
有什么建议?
这是ES6箭头函数的一个很好的用例,它与词汇绑定this.
以下是通过使用箭头函数代理对实例方法的调用来记录实例派生值的一般示例:
(在ES6 REPL上试一试,或者看看它在babel中编译.)
class A {
constructor(method) {
if(method) {
method()
return
}
this.callback()
}
message() {
return "a"
}
callback() {
console.log(this.message())
}
}
class B extends A {
constructor() {
super(() => this.callback())
}
message() {
return "b"
}
callback() {
console.log(this.message())
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这样做可以避免thisArg在我们调用之前立即引用新实例super.在您给出的示例中,这是这样实现的:
class MyButton extends Phaser.Button {
constructor(game) {
super(
game,
game.world.centerX,
game.world.centerY,
'buttonImage',
() => this.clickHandler()
);
}
clickHandler(button, pointer) {
//handle the clicking
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1640 次 |
| 最近记录: |