0

Let's say I have this global object:

funky_baby = {
    "wonk wonk": "clunk", 
    "zipee": "chugga chugga", 
    "ahoooga": "boioioioing"
};

And I want to access it using the string "funky_baby". I am currently using this method:

window["funky_baby"];

This doesn't seem like it will be very multi-browser friendly to me. Is there a better way to accomplish this task?

  • 2
    Maybe `window.funky_baby` – Danilo Valente May 29 '13 at 00:03
  • Based on what? That's the language *definition* for accessing properties. – Dennis May 29 '13 at 00:07
  • Please search first. There are *many duplicates*. I.e. http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets , – user2246674 May 29 '13 at 00:08
  • That is not a duplicate of my question. My question has to do with how different newer/older browsers deal with the "window" object! And as it turns out they don't all handle it the same way, so please read more carefully before assuming the role of thread police! – Morgan Freeman May 29 '13 at 00:51

3 Answers3

4

As explained in this question's accepted answer, your code is perfectly fine, as long as you don't want to iterate through its members in IE8 or earlier. You can, however, declare it as

window.funky_baby = {"wonk wonk", "zipee", "ahoooga"};

And you've solved that too :)

Community
  • 1
  • 1
Dragos Bobolea
  • 772
  • 7
  • 16
  • Great, thanks! I thought there might be an issue with IE8, which is why I asked. I think it still accounts for 15+% of our client base! – Morgan Freeman May 29 '13 at 00:13
3

That is perfectly "multi-browser" friendly.

obj["string"];

var string = "string";
obj[string];
obj.string;

All are totally valid. Even if you're accessing window, as long as you can guarantee that this program is meant for a web-browser, as window is guaranteed to be a part of the global DOM in that case.

Except that you don't have a real object, there.

var obj = {
    key1 : value1,
    key2 : value2
};

If you didn't have the values there, it would break.

Norguard
  • 26,167
  • 5
  • 41
  • 49
2

If you are trying to access a variable through its name a as a string (leaving aside that the object is not a real object), window["varName"] is the best way to do it.

This is only particularly useful if the variable you are trying to access varies in itself (e.g. access window["blue"] in one case but window["yellow"] in another:

var blue   = "Blue",
    yellow = "Yellow";

function (color) {
    console.log(window[color]);
}

If you are simply attempting to access that variable, just type the variable name:

console.log(funky_baby);
Albert Xing
  • 5,620
  • 3
  • 21
  • 40