class Foo {
constructor() {
this.foobar = "foobar";
}
bar() {
let _this = this;
return function() {
try {
alert("Attempt 1: "+foobar);//ReferenceError: foobar is not defined
myMethod();
} catch(err) {console.log(err);}
try {
alert("Attempt 2: "+this.foobar);//TypeError: this is undefined
this.myMethod();
} catch(err) {console.log(err);}
try{
alert("Attempt 3: "+_this.foobar);//Works!
_this.myMethod();
} catch(err) {console.log(err);}
}();
}
myMethod() {
alert("myMethod()");
}
}
new Foo().bar();
上面的例子是非常簡單的 - 裏面bar()
匿名函數是一個jQuery的呼叫最初,但問題的緣故,我沒有包括。
爲什麼不嘗試1和2的工作?我是否必須使用_this技巧來引用類變量/方法? 如何從嵌套函數引用類變量/方法?