Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object by name as string without eval

The code below does what I want, but I would like to avoid eval. Is there a function in Javascript that looks up an object by its name as defined by in a string?

myobject = {"foo" : "bar"}
myname = "myobject";
eval(myname);

Some context: I am using this for an application in which a large number of nodes in the dom has a html5 data-object attribute, which is used in the handler function to connect back to the model.

Edit: myobject is neither global nor local, it is defined in one of the parent frames of the handler.

like image 486
Jeroen Ooms Avatar asked Aug 12 '12 18:08

Jeroen Ooms


1 Answers

If variables are global then:

myobject = {"foo" : "bar"};
myname = "myobject";
window[myname].foo

DEMO

For local:

(function(){
    myobject = {"foo" : "bar"};
    myname = "myobject";
    alert( this[myname].foo );
})();

DEMO

like image 153
thecodeparadox Avatar answered Oct 02 '22 01:10

thecodeparadox