Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  193] [ 5]  / answers: 1 / hits: 37897  / 12 Years ago, sun, august 12, 2012, 12:00:00

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.


More From » jquery

 Answers
7

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


[#83689] Friday, August 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blair

Total Points: 384
Total Questions: 108
Total Answers: 86

Location: Northern Ireland
Member since Tue, May 5, 2020
4 Years ago
;