How to Execute a JavaScript Function when You have Its Name as a String
In this tutorial, we will discuss the two methods that are used to execute a function from string stored in a variable. Let’s discuss which method is preferable and safe for this kind of situation.
It is recommended to use the window object in HTML5 references the current window and all items within it. You can use the object to run a function in a string along with parameters to the function:
window["functionName"](arguments);
As this will not work with a namespace'd function you can use the following:
window["Namespace"]["functionName"](arguments); // succeeds
Here we suggest a flexible example:
You can call it like this:
executeFunctionByName("Namespace.functionName", window, arguments);
There is another method that is used often to resolve such situations, namely, eval(). However, be aware that using this method is not recommended. Let’s explain why you should not use this method.
The major and the first reason you should avoid using it is that the method is obsolete and may not be supported by newer browsers. It has some safety, optimization and debugging issues. Instead, we suggest a better and safer solution to your problem at the beginning of the tutorial.