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