从匿名函数访问JavaScript字段
如何从方法中的匿名函数中访问fiel? 如本例所示:从匿名函数访问JavaScript字段,javascript,class,anonymous-function,Javascript,Class,Anonymous Function,如何从方法中的匿名函数中访问fiel? 如本例所示: class Something { constructor (){ this.gax = “gax”; } doSomething(){ (function () { console.log(this.gax); }()); } } new Something().doSomething(); 这将导致“this”未定义的错误。 事先非常感
class Something {
constructor (){
this.gax = “gax”;
}
doSomething(){
(function () {
console.log(this.gax);
}());
}
}
new Something().doSomething();
这将导致“this”未定义的错误。
事先非常感谢,我搜索了几个小时后在网上找不到答案。
最好的,
lev在匿名函数中,
此
绑定到函数;它不再是指类
使用一个没有自己的this
绑定的
分类{
构造函数(){
this.gax=“gax”;
}
doSomething(){
(() => {
console.log(this.gax);
})();
}
}
新事物代码>
您可以使用apply
方法。apply()
方法调用具有给定此值的函数很抱歉,但是您需要匿名函数做什么?可能相关:……或者可能……或者大约六个其他函数,包括@Dale提到的函数。
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(function () {
console.log(this.gax);
}).apply(this);
}
}
new Something().doSomething();