views:

164

answers:

1

Before you ask... I don't plan to actually do this. It's bad practice for obvious reasons. I'm just curious if it is possible.

In javascript, you can use bracket syntax to make variable-variables in global scope:

var var_name  = 'my_var',
    var_value = 'my_value';

window[var_name] = var_value;

alert( my_var ); // Works! alerts user: 'my_value'

However, when you're inside of a function and you use the 'var' keyword, the variables you create are locally scoped to the function they are declared in. Is there some object that can be used with the bracket syntax (like window) to get access to the locally scoped variables? Something like this:

this_function[var_name] = var_value;

I doubt it's possible, but thought I'd ask just for kicks.

+2  A: 

No, there's no object you can use to access var variables within function contexts (even though they are properties of an object called the "variable object" of that execution context; the object has no exposed name and so cannot be accessed directly). The var thing in the global context is a bit of a special case, and you shouldn't rely on it (although the spec does define it). If you want to access those variables as properties of the global object (window, in the case of web browsers), explicitly assign them to window properties rather than using var, for clarity:

window.x = 'my value';

or if you prefer:

window["x"] = 'my value';

(Those two statements have identical results, both create/set a property called "x" on the window object.)

T.J. Crowder
I pretty much knew this would be the answer. Just wanted to hear it from someone else :p
spudly
Though if you wanted to, you could create a locally scoped *object* and use it in that way eg:function someFunc(){ var localVars = {}; localVars.variable1 = 'Hello'; alert(localVars["variable1"]);}Not entirely sure why you'd want to, but as with all things in javascript, I'm sure it would have some when other methods are too tedious or not flexible enough.
Graza
+1 For talking about the *Variable Object*, the Execution Context creation concept is not really widespread known... A good more in-depth article: http://is.gd/5cxyl
CMS