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

How to Pass a JavaScript Function as a Parameter Without Executing It?

Susan Sarandon
Release: 2024-12-13 17:10:20
Original
968 people have browsed it

How to Pass a JavaScript Function as a Parameter Without Executing It?

How to Pass a JavaScript Function as a Parameter (Without Execution)

When passing functions as parameters, it's crucial to avoid immediate execution within the "parent" function. This prevents unwanted side effects and potential security concerns with practices like eval().

Solution:

To pass a function as a parameter without immediate execution, simply remove the parentheses from its name:

addContact(entityId, refreshContactList);
Copy after login

This passes the function reference instead of calling it, allowing you to execute it later within the callback function.

Example:

Consider the following scenario:

function addContact(id, refreshCallback) {
    refreshCallback();
    // You can also pass arguments if you need to
    // refreshCallback(id);
}

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

addContact(1, refreshContactList);
Copy after login

In this example, the addContact function receives two parameters: entityId and refreshContactList. The refreshContactList function is passed as a reference without immediate execution. Within the addContact function, the refreshContactList function is invoked, triggering the alert.

The above is the detailed content of How to Pass a JavaScript Function as a Parameter Without Executing It?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template