[英]Keeping class this when calling button click function
Is there a way to keep the class this
when entering a click function from a button? 通过按钮输入单击功能时,是否可以将
this
保留为this
?
For example: 例如:
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
}
But I want to access this.obj
in foo()
. 但是我想在
foo()
访问this.obj
。
You need to bind foo
您需要绑定
foo
$("#someButton").click(this.foo.bind(this));
or use arrow function 或使用箭头功能
$("#someButton").click(() => this.foo());
Why are you not defining a parameter for the function foo: 为什么不为函数foo定义参数:
$("#someButton").click(function(){ foo(obj); }); foo(obj){ // work with obj ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.