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.
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 + "()");
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.
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();
or
let functionName = "sayHello"; let functionObj = window['sayHello']; functionObj();
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!