Executing JavaScript Functions with String Representation
Query: You have the name of a JavaScript function stored as a string and intend to invoke it later. How can you convert this string into a function pointer to subsequently invoke the function?
Answer:
function executeFunctionByName(functionName, context /*, args */) { // Retrieve arguments var args = Array.prototype.slice.call(arguments, 2); // Split the namespace into parts var namespaces = functionName.split("."); // Get the function name var func = namespaces.pop(); // Iterate through namespaces and get the context for (var i = 0; i < namespaces.length; i++) { context = context[namespaces[i]]; } // Apply the function with the context and arguments return context[func].apply(context, args); }
executeFunctionByName("My.Namespace.functionName", window, arguments);
This solution allows dynamic function execution based on a string representation, even for functions within namespaces. Consider the comprehensive solutions provided to handle this scenario effectively.
The above is the detailed content of How Can I Execute a JavaScript Function Using Its String Name?. For more information, please follow other related articles on the PHP Chinese website!