I can't seem to find a question that answers this directly.
I'd like to use a function argument as the name of a variable within that function.
e.g.,
test(var1);
function test(foo)
{
var foo = 'Hello world!'; // Set var1
}
alert(var1); // Hello world!
Can I use the brackets here (i.e., window.[ ])?
2 Answers 2
Comments
Er...okay, so this is almost certainly not a good idea.
Short answer: sorta. If you're running in a browser, you can do this:
var polluteGlobalNamespace = function(symbol) {
window[symbol] = "whatever";
};
polluteGlobalNamespace('foo');
console.log(foo);
But that only works for global variables. There is no way to do this with function-scoped variables, because JavaScript lacks first class environments.
But unless you're doing some deep dark metaprogramming, this isn't a good idea. It might be better to post the problem that you're trying to solve with this function to see what the idiomatic way to do it is.
obj[propNameExpression]. Then consider thatwindowevaluates to an Object and thus supports properties and normal property access (although some DOM/browser properties are "reserved"). That being said, usingwindow[prop], for an unconstrained prop value, is probably questionable. ConsidermyObject[prop]instead. You'll also need to pass in"var1"as a string value (or the identifier will be evaluated).