Javascript Reference Outer Shadow Variables from Inner Objec



快速问题 - 是否可以从 IIFE 引用阴影变量?我想引用全局中的a,这可能吗?

var a = 2;
(function foo(){
    var a = 3;
    console.log( a ); // 3
    console.log( this.a ); // I want to reference to the var a = 2 in global
})();
console.log( a ); // 2

这是可能的,(尽管不是最好的做法)。您可以引用窗口对象:

window.a = 2;
(function foo(){
    var a = 3;
    console.log(window.a);  // 2
...

最新更新