Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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 Python. So what I want to know is, how can I access a global variable when a "closer" scope also has a variable with the same name?

var a = "global";
function b(){
  var a = "local";
  var magic = ...; // somehow put "global" in magic
  console.log(magic); // should print "global"
}

In browser only, I figured out that you can use window.a to specify the global. Is there anything that works server-side as well?

like image 330
Coderer Avatar asked Sep 20 '12 15:09

Coderer


2 Answers

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();
like image 62
Denys Séguret Avatar answered Nov 03 '22 00:11

Denys Séguret


There is no standard to do that. For my own purposes, I always put my variables in a container where the name resembles the project name:

var PROJECT = {}; // Put all "globals" for "project" into this container

That way, I can collect all variables in one place and if I need to pass the "globals" around, I have to pass at most one reference.

like image 26
Aaron Digulla Avatar answered Nov 02 '22 22:11

Aaron Digulla