views:

32

answers:

2

Basically what I am after is this,

var foo = 'I am foo!';
alert(window['foo']);

// output = I am foo!

This does not work in a jQuery wrapper, I understand that it may be due to jQuery having renamed the window object or whatnot. If anyone has any inkling as to if this may be possible in a jQuery wrapper, I would appreciate the knowledge !

+2  A: 
foo = "I am foo!";

If you have a function scope around your var line, it'll define it as a local variable instead of a global variable. It's not jQuery "renaming the window object" or anything silly like that, it's just how var works. I'd personally doing

window.foo = "I am foo!";
// or
window["foo"] = "I am foo!";

though, to make it explicit you wanted to define a global variable. Or use a comment to say that.

Matti Virkkunen
Thank you for the answer. The idea was I would pull in a string, like, the id of an element such as 'mob', and their would be a variable also called 'mob'. What I wished was to target the variable with the string using the method above.
duckbox
@duckbox: And what's preventing you from doing that?
Matti Virkkunen
Ah, I have discovered the error of my ways. I was declaring the var AFTER the document.ready begins. If I place it BEFORE, it works fine. I should really head back to school ! Thank you for your help !
duckbox
+1  A: 

jQuery doesn't rename the window object - jQuery is actually under it (window.jQuery).

Try this:

window.foo = 'I am foo!';
alert(window.foo);
xil3