nathanbweb
nathanbweb

Reputation: 717

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

Upvotes: 4

Views: 1887

Answers (2)

Andries
Andries

Reputation: 1527

Every variable that is somehow related to the global object can be accessed globally. In browsers, the window variable represents the global object.

function a() {
  bvar = 3; // Accessible
  var cvar = 4; // Inaccessible
}

a();

alert(window.bvar === 3); // true
alert(window.cvar === 4); // false, cvar is undefined

// This refers here to the global object
alert(window.bvar === this.bvar); // true

Upvotes: 1

jAndy
jAndy

Reputation: 236172

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.

Upvotes: 4

Related Questions