Home >Web Front-end >JS Tutorial >Function References vs. Function Calls: When to Use Which?
Function References Versus Function Calls: Differentiating Their Roles
In programming, distinguishing between function references and function calls is crucial. A function reference holds an address to a function, while a function call executes the function immediately.
Understanding the Distinction
Consider the following code:
function hello() { alert("hi!"); } var elem = document.getElementById("btn"); elem.onclick = hello;
Here, elem.onclick assigns a function reference to the onclick property. The reference points to the hello function but does not execute it. This is necessary because onclick expects a reference to a function, not the execution of the function.
In contrast, consider this code:
element.onclick = funcRef();
This code executes the funcRef function immediately and assigns its return value (not the reference) to the onclick property. Avoid this approach as it may result in unexpected behavior, especially if the return value is not itself a function.
Guidelines for Function References and Function Calls
funcRef();
element.onclick = function () { // Code here };
Remember, the key difference lies in whether the function should be executed immediately or if merely a reference to it is required. By applying these guidelines, you can effectively manage function references and function calls in your code.
The above is the detailed content of Function References vs. Function Calls: When to Use Which?. For more information, please follow other related articles on the PHP Chinese website!