Question

If I want to access a variable define in the global context from within a scope where there already exists a variable with the same name:

var variable = 'value';
function someScope(variable){
    variable = 'not this';
    var global = Function('return this')();
    console.log('this > ', global.variable);
}

Is it possible to still access the global variable somehow?

Neither the global object nor getting the Global object works. (global.variable returns undefined)

Was it helpful?

Solution

If the variable is really global you can access it via global.name even if there are collisions with a local variable. For example

// notice there is not "var" here
variable = 'global';

function someScope() {
    var variable = 'local';
    console.log(variable);            // local
    console.log(global.variable);     // global
}

someScope();

However, if you define your variable with "var" at the top of the file (as you have it in your code) then it won't be global and you will get different results (i.e. global.variable will print undefined.)

OTHER TIPS

You can access an global JS variable through the window object, as each global variable is a property of the window object:

var var1 = 'Hello World!';

// stated on the global scope, is the same as
window.var1 = 'Hello World!';

You may also read those globals within a functions scope:

function() {
    console.log( window.var1 );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top