There is a much more comprehensive and complete answer to this question, which was answered by user Jason Bunting at the following link: How to execute a JavaScript function when I have its name as a string
Because this answer is in English, I will translate the content:
Do not use the function eval
, unless you are 100% sure you have no other alternative.
As has been mentioned, using something similar would be the best way to do it:
window["functionName"](arguments);
However, this will not work when the function uses namespaces:
window["My.Namespace.functionName"](arguments); // fallará
The following should be executed:
window["My"]["Namespace"]["functionName"](arguments); // funcionará
In order to make it easier and provide flexibility, here is a function to solve this:
function executeFunctionByName(functionName, context /*, args */) {
var args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
}
With the above code, you can execute the function as follows:
executeFunctionByName("Mi.Namespace.nombreDeFuncion", window, argumentos);
The second parameter is the context in which the function is executed, which can be modified according to your needs:
executeFunctionByName("Namespace.nombreDeFuncion", Mi, argumentos);