Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the value of a shadowed global variable?

Example:

var test = 'global value';

(function() {
    var test = 'local value';

    // how to get the 'global value' string
})();

Given the condition that the host environment is unknown, meaning that we cannot assume that the global object will be accessible via the window name. Also, the function is not allowed to receive any arguments!

like image 369
Šime Vidas Avatar asked Nov 24 '11 00:11

Šime Vidas


2 Answers

The fix

var test = 'global value';

(function() {
    var test2 = 'local value';

    console.log(test);
})();

The real solution is to fix your code so your not shadowing global variables you care about.

Eval work around

You can always use global eval, it's the most reliable.

Example

var test = 'global value';

function runEval(str) {
  return eval(str);
}

(function() {
    var test = 'local value';

    console.log(runEval("test"));
})();

If you don't like defining a global eval you can use Function to do it indirectly

Live Example

var test = 'global value';

(function() {
    var test = 'local value';

    console.log(new Function ("return test;") () );
})();

Miscellaneous hacks

The following works in non strict mode

(function () {
  var test = "shadowed";

  console.log(this !== undefined && this.test);
})();

And this hack works in broken implementations

(function() {
    var test = 'local value';

    try { delete test; } catch (e) { }

    console.log(test);
})();
like image 53
Raynos Avatar answered Oct 04 '22 23:10

Raynos


What about relying on its this as the global object (no explicit reference to window).

console.log(this.test);

jsFiddle.

You could also use an indirect call to eval() (execScript() is here for IE purposes, but feel free to ignore as you mentioned to not assume a browser).

console.log((window.execScript || eval)('test'));

jsFiddle.

like image 24
alex Avatar answered Oct 04 '22 22:10

alex