当从按钮输入点击函数时,有没有办法保留类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
。
最佳答案
您需要绑定(bind)foo
$("#someButton").click(this.foo.bind(this));
或使用箭头功能
$("#someButton").click(() => this.foo());
关于javascript - 调用按钮单击功能时保持类 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44242279/