Home > Web Front-end > JS Tutorial > body text

How to call a function from a function name stored in a string using JavaScript?

王林
Release: 2023-08-27 09:09:11
forward
1089 people have browsed it

如何使用 JavaScript 从存储在字符串中的函数名称调用函数?

We will use the eval() function to call a function from its name stored in a string. Evaluate() Function evaluates a string into JavaScript code. This allows us to call the function via Pass a string containing its name as an argument to the eval() function.

Example

This is a complete working example of how to use JavaScript to call a function from its name stored in a string -

// Define the function that we want to call
function sayHello() {
   console.log("Hello, world!");
}

// Store the function name as a string
let functionName = "sayHello";

// Use the `eval()` function to convert the string to a function call
eval(functionName + "()");
Copy after login
  • In the above example, we first define a simple function called sayHello(), which only logs "Hello, world!" to the console. Next, we define a variable called functionName that stores the string "sayHello", which is the name of the function we want to call.

  • Finally, we use the eval() function to convert the string functionName into a function call by concatenating it with the brackets () required to actually call the function.

  • The eval() function is a powerful but potentially dangerous feature of JavaScript that allows you to evaluate strings just like JavaScript code. Using eval() in production code is generally not recommended because it can be used to execute arbitrary code, which can be a security risk.

alternative method

It's worth mentioning that there are safer ways to call functions from function names stored in strings without using eval, such as -

let functionName = "sayHello";
let functionObj = window[functionName];
functionObj();
Copy after login

or

let functionName = "sayHello";
let functionObj = window['sayHello'];
functionObj();
Copy after login

These alternatives are safer than using eval because they do not execute arbitrary code but refer to the function directly by name.

The above is the detailed content of How to call a function from a function name stored in a string using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template