Created
February 18, 2017 01:01
-
-
Save fnicastri/8c872dd5ac5a50bf96ba0df3b0ab5443 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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