Home >Web Front-end >JS Tutorial >How to Safely Execute JavaScript Functions from Strings?
In JavaScript, you may encounter scenarios where you need to convert a string containing a function call into an actual function execution. Here's a comprehensive solution:
Prerequisites:
Solution:
<code class="js">var fn = window[settings.functionName];</code>
This step obtains a reference to the function identified by settings.functionName, which in this case is "clickedOnItem".
<code class="js">if(typeof fn === 'function') { fn(t.parentNode.id); }</code>
This step ensures that the retrieved value is indeed a function. If it is, it proceeds to execute the function with the specified argument.
In the provided example, the code would translate the string into a direct function call:
<code class="js">clickedOnItem(IdofParent);</code>
Additional Note:
While the eval() method can also evaluate strings as code, it is generally discouraged due to security concerns. The solution presented here provides a safer alternative.
The above is the detailed content of How to Safely Execute JavaScript Functions from Strings?. For more information, please follow other related articles on the PHP Chinese website!