shi*_*zou 0 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
}
Run Code Online (Sandbox Code Playgroud)
但我想访问this.obj在foo().
你需要绑定 foo
$("#someButton").click(this.foo.bind(this));
Run Code Online (Sandbox Code Playgroud)
或使用箭头功能
$("#someButton").click(() => this.foo());
Run Code Online (Sandbox Code Playgroud)