Alex Rivera | Logout

Access namespaced javascript object by string name without using eval

Asked 2011-02-13T00:42:09.280
14

I ran into a situation where I need access to a javascript object from the server. The server returns the string name of the function or object and based on other metadata I will evaluate the object differently.

Originally I was evaluating (eval([string])) and everything was fine. Recently I was updating the function to not use eval for security peace of mind, and I ran into an issue with namespaced objects/functions.

Specifically I tried to replace an eval([name]) with a window[name] to access the object via the square bracket syntax from the global object vs eval.

But I ran into a problem with namespaced objects, for example:

var strObjName = 'namespace.serviceArea.function';
// if I do
var obj = eval(strObjName); // works

// but if I do
var obj = window[strObjName]; // doesn't work

Can anyone come up with a good solution to avoid the use of eval with namespaced strings?

Edit
Report

1 Answer

-1

The following assumes that the parts of strObjName are separated by . and loops through starting at window until it gets down to the function you want:

var strObjParts = strObjName.split('.');
var obj = window;
for(var i in strObjParts) {
  obj = obj[strObjParts[i]];
}
answered 2011-02-13T00:59:29.043

Your Answer