javascript tutorial - [Solved-5 Solutions] Name as a string - javascript - java script - javascript array



Problem:

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

Solution 1:

Don't use eval unless we 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);
click below button to copy the code. By JavaScript tutorial team

That, however, will not work with a namespace'd function:

window["My.Namespace.functionName"](arguments); // fail
click below button to copy the code. By JavaScript tutorial team

This is how we would do that:

window["My"]["Namespace"]["functionName"](arguments); // succeeds
click below button to copy the code. By JavaScript tutorial team

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);
}
click below button to copy the code. By JavaScript tutorial team

we would call it like so:

executeFunctionByName("My.Namespace.functionName", window, arguments);
click below button to copy the code. By JavaScript tutorial team

Solution 2:

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);
}
click below button to copy the code. By JavaScript tutorial team

Solution 3:

can say

window["foo"](arg1, arg2);
click below button to copy the code. By JavaScript tutorial team

or as many others have suggested, you can just use eval:

eval(fname)(arg1, arg2);
click below button to copy the code. By JavaScript tutorial team
eval(fname)(arg1, arg2);
click below button to copy the code. By JavaScript tutorial team

Solution 4:

do this:

var codeToExecute = "My.Namespace.functionName()";
var tmpFunc = new Function(codeToExecute);
tmpFunc();
click below button to copy the code. By JavaScript tutorial team

Solution 5:

var customObject = {
  customFunction: function(param){...}
};
click below button to copy the code. By JavaScript tutorial team

Then we can call:

customObject['customFunction'](param);
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Name as a string