在呼叫按钮点击功能时,请保留此类



从按钮输入点击函数时,是否有一种方法可以保留类this

例如:

class MyClass extends FooClass{
  constructor (obj) {
    super (obj)
    this.obj= obj;
    $("#someButton").click(this.foo);
  }
  foo(){
    this.obj; // undefined because this is now #someButton and not MyClass 
  }

,但我想在foo()中访问this.obj

您需要绑定foo

$("#someButton").click(this.foo.bind(this));

或使用箭头功能

$("#someButton").click(() => this.foo());

为什么不定义函数的参数:

$("#someButton").click(function(){
  foo(obj);
});
foo(obj){
  // work with obj ... 
}

最新更新