Home > Web Front-end > JS Tutorial > How to Safely Invoke a JavaScript Function from a String Without Using `eval()`?

How to Safely Invoke a JavaScript Function from a String Without Using `eval()`?

Mary-Kate Olsen
Release: 2024-10-29 07:37:30
Original
476 people have browsed it

How to Safely Invoke a JavaScript Function from a String Without Using `eval()`?

Invoking a Javascript Function Call from a String

This question addresses the challenge of converting a string representing a function call, such as "settings.functionName '(' t.parentNode.id ')'", into an actual function invocation. The goal is to execute the function as if the string had been directly entered as a function call, without using eval() which is discouraged due to security concerns.

Solution:

The provided solution suggests an alternative approach by leveraging the window object to obtain a reference to the function. Here's an updated and more detailed explanation:

<code class="javascript">// Store the function name extracted from the string as a variable
var functionName = settings.functionName;

// Check if the function exists in the global scope using window
if (typeof window[functionName] === 'function') {
  // If the function exists, invoke it with the specified argument
  window[functionName](t.parentNode.id);
}</code>
Copy after login

Example:

Consider the following settings object:

<code class="javascript">window.settings = {
  functionName: 'clickedOnItem',
};</code>
Copy after login

And the following function definition:

<code class="javascript">function clickedOnItem(nodeId) {
  // Function body
}</code>
Copy after login

Using the solution above, we can invoke the clickedOnItem function with the t.parentNode.id argument as follows:

<code class="javascript">// Extract the function name from the settings object
var functionName = settings.functionName;

// Check if the function exists in the global scope
if (typeof window[functionName] === 'function') {
  // Invoke the function with the specified argument
  window[functionName](t.parentNode.id);
}</code>
Copy after login

This method allows us to dynamically invoke functions based on a string representation without resorting to eval() or compromising security.

The above is the detailed content of How to Safely Invoke a JavaScript Function from a String 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