使用 ES6 将实例方法传递给 super 类

Passing an instance method to super with ES6 classes

据我了解,在调用 super( ) 之前,this 在构造函数中不可用。

不过,在引用实例方法时,我们需要在方法前加上this前缀。那么如何将实例方法传递给 super( )?

例如在Phaser framework, there is a Buttonclass。构造函数接受点击事件的回调:

Constructor
new Button(game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)

callback - The function to call when this Button is pressed.
callbackContext - The context in which the callback will be called (usually 'this').

我想要自己的按钮class,我这样定义:

class MyButton extends Phaser.Button {
    constructor(game) {
        super(game, game.world.centerX, game.world.centerY, 'buttonImage');
    }

    clickHandler(button, pointer) {
       //handle the clicking
    }
} 

那么我如何将 clickHandler 传递给 super

this.clickHandler 给出错误 [Build Error] 'this' is not allowed before super() while parsing file: .... 并且只传递 clickHandler 给我一个运行时错误 Uncaught ReferenceError: clickHandler is not defined.

有什么建议吗?

这是 ES6 arrow functions 的一个很好的用例,它在词法上绑定到 this

这是一个通过使用箭头函数代理对实例方法的调用来记录实例派生值的通用示例:

(Try it out on an ES6 REPL, or see it compile in 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())
  }
}

如您所见,这样做可以避免在调用 super 之前立即引用新实例的 thisArg。在您给出的示例中,这是这样实现的:

class MyButton extends Phaser.Button {
    constructor(game) {
        super(
            game,
            game.world.centerX,
            game.world.centerY,
            'buttonImage',
            () => this.clickHandler()
        );
    }

    clickHandler(button, pointer) {
       //handle the clicking
    }
}