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

How Can I Call a JavaScript Function Using Its Name Stored as a String?

Mary-Kate Olsen
Release: 2024-12-26 04:03:09
Original
466 people have browsed it

How Can I Call a JavaScript Function Using Its Name Stored as a String?

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);
Copy after login

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);
Copy after login

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);
}
Copy after login

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);
Copy after login

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!

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