Parentheses in JavaScript Function Calls
In JavaScript, calling a function without parentheses may seem innocuous when no arguments are involved. However, a subtle difference arises between the two syntaxes:
window.onload = initAll();
window.onload = initAll;
When Parentheses Are Used:
Using parentheses in a function call, as in the first example, executes the function immediately. The result of the function execution, if any, is then assigned to the variable or property receiving the function call, in this case, window.onload. This execution is usually undesirable when you intend to assign the function itself to the listener.
When Parentheses Are Omitted:
Omitting parentheses, as in the second example, assigns the function reference directly to the variable or property. The function will only be executed when the listener or event triggers it, ensuring the intended behavior.
Additional Note:
Another variation you may encounter is:
window.onload = () => initAll();
This uses an arrow function wrapped around initAll. It creates a function that immediately calls initAll upon invocation. However, because the outer function is assigned to window.onload, it ensures that initAll is executed only on the load event.
The above is the detailed content of What's the Difference Between `window.onload = initAll();` and `window.onload = initAll;` in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!