In PHP you can do amazing/horrendous things like this:
$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1
Is there any way of doing something like this with Javascript?
E.g. if I have a var name = 'the name of the variable';
can I get a reference to the variable with name name
?
what they mean is no, you can't. there is no way to get it done. so it was possible you could do something like this
having a create function just like the one implemented in ECMAScript 5.
eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:
Try this...
Since ECMA-/Javascript is all about
Objects
andContexts
(which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).So if you create variables like this:
In the Global scope (= NO function context), you implicitly write those variables into the Global object (=
window
in a browser).Those can get accessed by using the "dot" or "bracket" notation:
or
This only works for the global object in this particular instance, because the Variable Object of the Global Object is the
window
object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:new
creates a new instance of a self-defined object (context). Withoutnew
the scope of the function would be alsoglobal
(=window). This example would alertundefined
and1
respectively. If we would replacethis.a = 1; this.b = 2
with:Both alert outputs would be undefined. In that scenario, the variables
a
andb
would get stored in the Activation Object fromfoobar
, which we cannot access (of course we could access those directly by callinga
andb
).This is an example :
Another example :
So, the value "coco" of myVariable becomes a variable coco.
Because all the variables in the global scope are properties of the Window object.
If you don't want to use a global object like window or global (node), you can try something like this: