Can I explicitly reference a JavaScript global variable that's been shadowed by a local with the same name?

前端 未结 5 537
死守一世寂寞
死守一世寂寞 2020-12-10 11:40

I\'ve seen tons of posts about the difference between global and function scope in JavaScript, far too many to link here. I\'ve also seen my exact question asked about Pyth

5条回答
  •  我在风中等你
    2020-12-10 12:31

    If it's really a global (i.e. not just in the outer scope), you can do this :

    var magic = (function(name){return this[name]}).call(null, "a");
    

    From ECMAScript's documentation (10.4.3) :

    Entering Function Code

    The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisArg, and a caller provided argumentsList:

    If the function code is strict code, set the ThisBinding to thisArg. Else if thisArg is null or undefined, set the ThisBinding to the global object.

    Note that you can't test this in jsFiddle, as the global scope isn't where you define your a.

    Demonstration:

    var a = "global";
    
    function b(){
      var a = "local";
      var magic = (function(name){return this[name]}).call(null, "a");
      document.body.textContent = 'a: '+JSON.stringify(magic); // print "global"
    }
    
    b();

提交回复
热议问题