[英]Passing an instance method to super with ES6 classes
As I understand things, this
is not available inside the constructor before super( )
is called. 据我所知,在调用super( )
之前, this
在构造函数中是不可用的。
Still, when referring to instance methods, we need to prefix the method with this
. 但是,在引用实例方法时,我们需要在方法前加上this
。 So how is it possible to pass a instance method to super( )
? 那么怎样才能将实例方法传递给super( )
?
eg In the Phaser framework , there is a Button
class. 例如,在Phaser框架中 ,有一个Button
类。 The constructor takes a callback for the click-event: 构造函数对click事件进行回调:
Constructor 构造函数
new Button(game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)
callback - The function to call when this Button is pressed. callback - 按下此按钮时调用的函数。
callbackContext - The context in which the callback will be called (usually 'this'). callbackContext - 将调用回调的上下文(通常为“this”)。
I want my own button class, which I define like this: 我想要我自己的按钮类,我定义如下:
class MyButton extends Phaser.Button {
constructor(game) {
super(game, game.world.centerX, game.world.centerY, 'buttonImage');
}
clickHandler(button, pointer) {
//handle the clicking
}
}
So how will I pass the clickHandler
to super
? 那么我如何将clickHandler
传递给super
?
this.clickHandler
gives the error [Build Error] 'this' is not allowed before super() while parsing file: ....
and passing just clickHandler
gives me a runtime error of Uncaught ReferenceError: clickHandler is not defined
. this.clickHandler
[Build Error] 'this' is not allowed before super() while parsing file: ....
提供错误[Build Error] 'this' is not allowed before super() while parsing file: ....
并且只传递clickHandler
给我一个Uncaught ReferenceError: clickHandler is not defined
的运行时错误Uncaught ReferenceError: clickHandler is not defined
。
Any suggestions? 有什么建议么?
This is a good use-case for ES6 arrow functions , which are bound lexically to this
. 这是一个很好的用例为ES6箭头的功能 ,这是词法绑定this
。
Here is a generic example of logging an instance-derived value by proxying the call to the instance method with an arrow function: 以下是通过使用箭头函数代理对实例方法的调用来记录实例派生值的一般示例:
( Try it out on an ES6 REPL , or see it compile in babel .) ( 在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())
}
}
As you can see, doing this allows us to avoid immediately referencing the thisArg
of our new instance before our call to super
. 正如您所看到的,这样做可以避免在调用super
之前立即引用新实例的thisArg
。 In your given example this is implemented like this: 在您给出的示例中,这是这样实现的:
class MyButton extends Phaser.Button {
constructor(game) {
super(
game,
game.world.centerX,
game.world.centerY,
'buttonImage',
() => this.clickHandler()
);
}
clickHandler(button, pointer) {
//handle the clicking
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.