4

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nathanbweb
  • 717
  • 1
  • 11
  • 26

2 Answers2

4
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.

jAndy
  • 231,737
  • 57
  • 305
  • 359
1

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andries
  • 1,547
  • 10
  • 29
  • thanks, that's helpful. so bvar is accessible because it's a key, or because it isn't a variable? – nathanbweb Feb 21 '13 at 14:40
  • 1
    In JavaScript everything can be seen as an array. So, a function is an array with properties, and the global object can be seen as a array to. The function a() and bvar are both 'items' / properties on the global object. (every variable declared without the var prefix will leak into the global object.) so, window.a and window.bvar are accessable. cvar is declared inside a function and becomes a property of the functions' activation object'. Properties of activation object of functions are not accessable outside the function scope. Hope this helps, space is little here to explain this. – Andries Feb 21 '13 at 14:58
  • 1
    @Andries: I'd rather say everything is an object. Arrays are special types of objects. – Felix Kling Feb 21 '13 at 15:05
  • 1
    @Felix: True, thats why i carefully expressed myself by saying 'can be seen as'. I wanted to stress the array-behavior of JavaScript like: window['cvar'] === window.cvar. But you also right. Maybe we should say, everything is an special type of an object.:) – Andries Feb 21 '13 at 15:29