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>
Example:
Consider the following settings object:
<code class="javascript">window.settings = { functionName: 'clickedOnItem', };</code>
And the following function definition:
<code class="javascript">function clickedOnItem(nodeId) { // Function body }</code>
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>
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!