Home > Web Front-end > JS Tutorial > How Can I Execute a JavaScript Function Using Its String Name?

How Can I Execute a JavaScript Function Using Its String Name?

Linda Hamilton
Release: 2024-12-19 10:27:16
Original
696 people have browsed it

How Can I Execute a JavaScript Function Using Its String Name?

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:

  • Avoid eval: Utilize safer alternatives like window["functionName"](arguments) or window"My"["functionName"](arguments).
  • Convenience Function: Implement a function like executeFunctionByName, as seen below:
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);
}
Copy after login
  • Invocation: Use the convenience function as follows:
executeFunctionByName("My.Namespace.functionName", window, arguments);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template