HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to execute a JavaScript function when I have its name as a string

Submitted by: @import:stackoverflow-api··
0
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 namespace.namespace.function(args[...]).

Solution

Don't use 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); // fail


This is how you would do that:

window["My"]["Namespace"]["functionName"](arguments); // succeeds


In 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); // fail
window["My"]["Namespace"]["functionName"](arguments); // succeeds
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);
}
executeFunctionByName("My.Namespace.functionName", window, arguments);

Context

Stack Overflow Q#359788, score: 1680

Revisions (0)

No revisions yet.