在javascript中保护全局引用

Shr*_*low 5 javascript scopes

以下javascript代码允许您访问全局对象(window/worker).

(new function Outer(){
    console.log(this); /* The object */
    (function(){ // This function could be a 3rd Party function 
        console.log(this); /* window !!*/
    })();
});
Run Code Online (Sandbox Code Playgroud)

有没有办法可以确保内部总是能够引用外部的上下文.

我知道我能做到

(new function Outer(){
    'use strict';
    console.log(this); /* The object */
    (function(){ // This function could be a 3rd Party function 
        console.log(this); /* undefined ? !!*/
    })();
});
Run Code Online (Sandbox Code Playgroud)

但这导致this未定义.

编辑

我知道bind,但如果内部函数是嵌套的.比如说像

(function(){

    (function(){
        (function(){
           console.log(this);// undefined
        })();

    })();

}).bind(this)();
Run Code Online (Sandbox Code Playgroud)

我想要的是:外{}而不是使用变量引用外部: - |

PSL*_*PSL 7

你可以使用function.call.

new function Outer(){
    'use strict';
    console.log(this); 
    (function(){ // This function could be a 3rd Party function 
        console.log(this);  //<-- Now it will it the one from the outer scope
    }).call(this);
}; // You don't need to invoke this explicitly here with () since you are invoking it already with new keyword so constructor invocation doesnt need ()
Run Code Online (Sandbox Code Playgroud)

或者最好的选择是将外部缓存在外部并在内部范围内的任何位置使用它.

new function Outer(){
        'use strict';
        var self = this;
        console.log(this); 
        (function(){ // This function could be a 3rd Party function 
            console.log(self);  //<-- Now it will it the one from the outer scope
        })();
 };
Run Code Online (Sandbox Code Playgroud)