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.
Local Variable Solution:
You could make all objects that you want to access with a string properties of another object. For example:
var objectHolder = {
myobject: {"foo" : "bar"},
myobject2: {"foo" : "bar"},
myobject3: {"foo" : "bar"}
};
And then access your desired object like this:
var desiredObject = objectHolder["myobject"];
Global Variable Solution:
You can access global variables using a string like this:
window["myobject"];
If variables are global then:
myobject = {"foo" : "bar"};
myname = "myobject";
window[myname].foo
For local:
(function(){
myobject = {"foo" : "bar"};
myname = "myobject";
alert( this[myname].foo );
})();
since window is a global namespace, you could simply use
window[myname]