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?
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().
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With