Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从匿名函数访问JavaScript字段_Javascript_Class_Anonymous Function - Fatal编程技术网

从匿名函数访问JavaScript字段

从匿名函数访问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”未定义的错误。 事先非常感

如何从方法中的匿名函数中访问fiel? 如本例所示:

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();