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
Release: 2024-11-29 04:19:09
Original
162 people have browsed it

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);
Copy after login

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);
Copy after login

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!

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