snippetjavascriptCritical
How to execute a JavaScript function when I have its name as a string
Viewed 0 times
howfunctionhavenamewhenitsstringexecutejavascript
Problem
I have the name of a function in JavaScript as a string. How do I convert that into a function pointer so I can call it later?
Depending on the circumstances, I may need to pass various arguments into the method too.
Some of the functions may take the form of
Depending on the circumstances, I may need to pass various arguments into the method too.
Some of the functions may take the form of
namespace.namespace.function(args[...]).Solution
Don't use
As has been mentioned, using something like this would be the best way to do it:
That, however, will not work with a namespace'd function:
This is how you would do that:
In order to make that easier and provide some flexibility, here is a convenience function:
You would call it like so:
Note, you can pass in whatever context you want, so this would do the same as above:
eval unless you absolutely, positively have no other choice.As has been mentioned, using something like this would be the best way to do it:
window["functionName"](arguments);That, however, will not work with a namespace'd function:
window["My.Namespace.functionName"](arguments); // failThis is how you would do that:
window["My"]["Namespace"]["functionName"](arguments); // succeedsIn order to make that easier and provide some flexibility, here is a convenience function:
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);
}You would call it like so:
executeFunctionByName("My.Namespace.functionName", window, arguments);Note, you can pass in whatever context you want, so this would do the same as above:
executeFunctionByName("Namespace.functionName", My, arguments);Code Snippets
window["functionName"](arguments);window["My.Namespace.functionName"](arguments); // failwindow["My"]["Namespace"]["functionName"](arguments); // succeedsfunction 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);
}executeFunctionByName("My.Namespace.functionName", window, arguments);Context
Stack Overflow Q#359788, score: 1680
Revisions (0)
No revisions yet.