Skip to content

Instantly share code, notes, and snippets.

@ahvonenj
Created June 16, 2017 10:18
Show Gist options
  • Save ahvonenj/36b94fa5f45937b093f419eac582c420 to your computer and use it in GitHub Desktop.
Save ahvonenj/36b94fa5f45937b093f419eac582c420 to your computer and use it in GitHub Desktop.
How to execute a JavaScript function when I have its name as a string
// http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string
function Exec(functionName, context)
{
if(typeof functionName === 'undefined')
{
console.error('Could not execute undefined function');
return function() {}
}
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment