Car*_*los 5 javascript oop class this
我在 Javascript 中编程面向对象时遇到问题。我有以下几点:
class Foo{
constructor(){...}
...
a_needed_method(){...}
...
a_method(){
...
jsObject.on("click",function(params){
this.a_needed_method();
});
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,如果我a_needed_method使用this那里调用该方法,则this引用控制onclick事件的匿名函数。我如何a_needed_method()从这个匿名函数调用?
您可以使用箭头函数来保留词法 this:
jsObject.on("click", params => {
this.a_needed_method();
});
Run Code Online (Sandbox Code Playgroud)
您可以使用旧的that = this:
var that = this;
jsObject.on("click", function (params) {
that.a_needed_method();
});
Run Code Online (Sandbox Code Playgroud)