Home >Web Front-end >JS Tutorial >How to Pass Functions as Parameters in JavaScript Without Immediate Execution?

How to Pass Functions as Parameters in JavaScript Without Immediate Execution?

DDD
DDDOriginal
2024-11-28 08:19:10976browse

How to Pass Functions as Parameters in JavaScript Without Immediate Execution?

Passing Functions as Parameters in JavaScript

In JavaScript, it is possible to pass functions as parameters to other functions without invoking them prematurely. This can be useful when you want to defer the execution of a function until a later point in time.

Problem:

When passing a function as a parameter, it is crucial to avoid executing it immediately. For example, the following code executes refreshContactList() when it is passed as a parameter to addContact():

addContact(entityId, refreshContactList());

Solution:

To pass a function reference without executing it, simply remove the parentheses:

addContact(entityId, refreshContactList);

This technique allows you to pass the function as a parameter without triggering its invocation. Here is an example that illustrates how to pass a function as a parameter and execute it later:

function addContact(id, refreshCallback) {
    refreshCallback(); // Execute the function passed as the second parameter
}

function refreshContactList() {
    alert('Hello World');
}

addContact(1, refreshContactList);

In this example, the addContact() function takes two parameters: id and refreshCallback. When the addContact() function is called, the refreshCallback argument is passed a reference to the refreshContactList() function. The refreshContactList() function is not executed until it is called within the addContact() function.

The above is the detailed content of How to Pass Functions as Parameters in JavaScript 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