Skip to content

Instantly share code, notes, and snippets.

@fnicastri
Created February 18, 2017 01:01
Show Gist options
  • Save fnicastri/8c872dd5ac5a50bf96ba0df3b0ab5443 to your computer and use it in GitHub Desktop.
Save fnicastri/8c872dd5ac5a50bf96ba0df3b0ab5443 to your computer and use it in GitHub Desktop.
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 = [].slice.call(arguments).splice(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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment