This question already has answers here:
How to access the correct `this` inside a callback?
                                
                                    (10个回答)
                                
                        
                                5年前关闭。
            
                    
我想知道是否可以从以下代码中的window.updateFoo()访问foo:

function f1 () {
    'use strict';
    this.x = {};
    this.x.foo = 0;

    window.updateFoo = function(val){
       this.x.foo = val;       // Obviously wrong since 'this' doesn't refer to f1 now. Uncaught TypeError: Cannot set property 'foo' of undefined
    };
    window.updateFoo(20);      // Try changing the value of this.x.foo?
}

最佳答案

调用window.updateFoo时,将在window的上下文中调用它。最好的选择是将this保存在变量中,然后在函数中使用它:

function f1 () {
    'use strict';
    this.x = {};                // Object for 'const' variables
    this.x.foo = 0;

    var _this = this;

    window.updateFoo = function(val){
       _this.x.foo = val;       // Use saved version
    };
    window.updateFoo(20);      // Try changing the value of this.x.foo?
}


另一个选项(但仅在f1中有效)是在特定上下文中调用updateFoo

window.updateFoo.call(this, 20);

07-24 09:30