Home >Web Front-end >JS Tutorial >How to Pass a JavaScript Function as a Parameter Without Immediate Execution?

How to Pass a JavaScript Function as a Parameter Without Immediate Execution?

Barbara Streisand
Barbara StreisandOriginal
2024-11-29 04:19:09165browse

How to Pass a JavaScript Function as a Parameter Without Immediate Execution?

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!

Statement:
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