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
Mary-Kate OlsenOriginal
2024-11-02 06:22:02777browse

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 + ')'

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);
}

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 */
};

Later in the code, the following function is defined:

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

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);
}

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!

Statement:
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