Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access namespaced javascript object by string name without using eval

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?

like image 696
Josiah Ruddell Avatar asked Feb 13 '11 00:02

Josiah Ruddell


People also ask

What can I use instead of eval in Javascript?

An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().

How to call function from it name stored in a string using JavaScript?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How do you use a function name as a string?

You just need convert your string to a pointer by window[<method name>] . example: var function_name = "string"; function_name = window[function_name]; and now you can use it like a pointer.


1 Answers

You could split on . and resolve each property in turn. This will be fine so long as none of the property names in the string contain a . character:

var strObjName = 'namespace.serviceArea.function';
var parts = strObjName.split(".");
for (var i = 0, len = parts.length, obj = window; i < len; ++i) {
    obj = obj[parts[i]];
}
alert(obj);
like image 64
Tim Down Avatar answered Oct 04 '22 21:10

Tim Down