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.
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:
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!