在调用按钮点击功能

时间:2017-05-29 12:15:50

标签: javascript jquery ecmascript-6

从按钮进入点击功能时,有没有办法保持班级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 
  }

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

2 个答案:

答案 0 :(得分:5)

您需要绑定foo

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

或使用箭头功能

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

答案 1 :(得分:-1)

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



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


foo(obj){
  // work with obj ... 
}