Javascript: interpret string as object reference?

Possible duplicate:
Use Javascript variable as object name

How do I get JS to treat a string as a reference to a previously defined object? Simplified:

var myObject = new MyObject(); var myString = "myObject"; var wantThisToWork = myString.myproperty; 
+18
javascript
Jun 08 '12 at 17:20
source share
4 answers

If the variable is in the global scope, you can access it as a property of the global object

 var a = "hello world"; var varName = "a"; console.log( window[varName] ); // outputs hello world console.log( this[varName] ); // also works (this === window) in this case 

However, if it is a local variable, the only way is to use eval ( disclaimer )

 function () { var a = "hello world"; var varName = "a"; console.log( this[varName] ); // won't work console.log( eval(varName) ); // Does work } 

If you cannot put your dynamic variables in an object and access it as a property

 function () { var scope = { a: "hello world"; }; var varName = "a"; console.log( scope[varName] ); // works } 
+22
Jun 08 '12 at 17:27
source share

You can use the eval function.

 eval(myString).myproperty 

Be careful with eval, though if this is what the user enters, he will execute any javascript code!

+7
Jun 08 2018-12-12T00:
source share

The only way I think is to use eval. But, as they say, eval is evil, but not in a controlled environment. It is possible, but I do not recommend using eval if absolutely necessary.

 var myObject = new MyObject(); var myString = "myObject"; var wantThisToWork = eval(myString).myproperty; 
+6
Jun 08 2018-12-12T00:
source share

Use eval ()

 var myObject = {}; myObject.myproperty = "Hello"; var myString = "myObject"; var wantThisToWork = eval(myString).myproperty; 
+5
Jun 08 '12 at 17:30
source share



All Articles