Search code examples
javascriptvariablesglobal-variables

Using 'window' with a local variable for global access in JavaScript


I'd like to access a local variable globally (without changing the namespace or location of the variable). I read that I could use 'window.', but it's not working:

var myNameSpace = {
        window.localVar : 'foo'
    };

alert(window.localVar);  // Not working

JSFiddle

Can something like this work?

Also, I've read about the risks of global variables. If I'm nearly certain a variable's name isn't at risk to be reused, is it safe?

$myTotallyUniqueVarName

Solution

  • var myNameSpace = { };
    
    myNameSpace.localVar = window.localVar = 'foo';
    

    You can't access another object when defining the key from another object, like you tried. But you certainly can create multiple references/assignments to the same value, like shown above.

    However, be aware that we assigning a primitive value in this case, that means, window.localVar and myNameSpace.localVar will hold their own unique value. Any change will not reflect on the other side.