首页 > 解决方案 > 来自匿名函数的 JavaScript 字段访问

问题描述

如何从方法内的匿名函数中访问字段?就像在这个例子中:

class Something {
    constructor (){
        this.gax = “gax”;
    }
    doSomething(){
        (function () {
           console.log(this.gax);
        }());
    }
}
new Something().doSomething();

这将导致“this”未定义的错误。非常感谢您,搜索了几个小时后,我在网上找不到答案。最好的,列夫

标签: javascriptclassanonymous-function

解决方案


在您的匿名函数中,this绑定到该函数;它不再指类。

请改用箭头函数,它没有自己的this绑定。

class Something {
    constructor (){
        this.gax = "gax";
    }
    doSomething(){
        (() => {
           console.log(this.gax);
        })();
    }
}
new Something().doSomething();

或者,您可以使用类似.call(),.apply().bind():

class Something {
    constructor (){
        this.gax = "gax";
    }
    doSomething(){
        (function() {
           console.log(this.gax);
        }).call(this);
    }
}
new Something().doSomething();


推荐阅读