Pass JavaScript Function as Parameter without Execution
It can be problematic when passing functions as parameters and triggering their execution prematurely. Instead of using eval() or incurring the drawbacks of immediate function invocation, there's a simpler solution.
To pass a JavaScript function as a parameter without executing it in the parent function, simply remove the parentheses after the function name:
addContact(entityId, refreshContactList);
By omitting the parentheses, you're essentially passing the reference to the function, allowing it to be called within the parent function as needed.
Here's an example to illustrate:
function addContact(id, refreshCallback) { refreshCallback(); // Call the passed function } function refreshContactList() { alert('Hello World'); } addContact(1, refreshContactList);
In this example, refreshCallback references the refreshContactList function without executing it. When the addContact function calls refreshCallback(), refreshContactList is executed.
The above is the detailed content of How to Pass a JavaScript Function as a Parameter Without Immediate Execution?. For more information, please follow other related articles on the PHP Chinese website!