Calling a JavaScript Function by Name Stored in a String
In certain scenarios, you may encounter a situation where you possess the function name as a string and need to execute it. To achieve this, follow these steps:
Method 1: For Flat Functions
For functions that are not part of a namespace, use the following syntax:
window["functionName"](arguments);
Method 2: For Namespaced Functions
For functions within namespaces, the following syntax is necessary:
var namespaces = functionName.split("."); var func = namespaces.pop(); for (var i = 0; i < namespaces.length; i++) { context = context[namespaces[i]]; } context[func].apply(context, args);
Method 3: Using a Convenience Function
To simplify the process, you can utilize the following 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); }
Calling the Function
To call the function using any of the methods, specify the function name and context as shown below:
executeFunctionByName("My.Namespace.functionName", window, arguments);
The above is the detailed content of How Can I Call a JavaScript Function Using Its Name Stored as a String?. For more information, please follow other related articles on the PHP Chinese website!