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!
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.
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;") () );
})();
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);
})();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With