Home > Web Front-end > JS Tutorial > How to Convert a String into a Function Call in JavaScript Without Using `eval`?

How to Convert a String into a Function Call in JavaScript Without Using `eval`?

Mary-Kate Olsen
Release: 2024-11-02 06:22:02
Original
774 people have browsed it

How to Convert a String into a Function Call in JavaScript Without Using `eval`?

Converting a String into a Function Call in JavaScript

Question

You have a string representing a function call, such as:

settings.functionName + '(' + t.parentNode.id + ')'
Copy after login

You want to convert this string into an actual function call, but without using eval.

Solution

Instead of using eval, you can use the following code:

var fn = window[settings.functionName];
if(typeof fn === 'function') {
    fn(t.parentNode.id);
}
Copy after login

This code:

  1. Obtains a reference to the function by accessing the global window object and using the settings.functionName property as the key.
  2. Checks if the obtained value is a function.
  3. If it is a function, calls it with the desired argument.

Example

Consider the following settings object:

/* Somewhere: */
window.settings = {
  /* [..] Other settings */
  functionName: 'clickedOnItem'
  /* , [..] More settings */
};
Copy after login

Later in the code, the following function is defined:

function clickedOnItem (nodeId) {
  /* Some cool event handling code here */
}
Copy after login

Now, you can use the code presented in the solution to make a function call:

/* Even later */
var fn = window[settings.functionName]; 
if(typeof fn === 'function') {
    fn(t.parentNode.id);
}
Copy after login

This will result in the clickedOnItem function being called with the t.parentNode.id as the argument.

The above is the detailed content of How to Convert a String into a Function Call in JavaScript Without Using `eval`?. 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