Home >Web Front-end >JS Tutorial >JavaScript Function Calls: Empty Parentheses – Immediate Invocation or Reference Assignment?
Calling a function with empty parentheses or without parentheses at all may seem inconsequential for functions without arguments. However, a closer examination reveals a subtle distinction.
Consider the following two examples:
window.onload = initAll();
window.onload = initAll;
1. Immediate Invocation:
In the first example, the empty parentheses invoke the initAll() function immediately, and the return value is assigned to window.onload. Typically, this is not the desired behavior because initAll should execute when the onload event occurs.
2. Reference Assignment:
In the second example, the initAll function itself is assigned to window.onload. This means that the function will not execute until the load event is triggered. This approach ensures that the event handler is correctly set up.
In JavaScript, functions are first-class objects. This means they can be stored in variables, passed as arguments, and assigned as properties. This is why the following syntax is valid:
window.onload = () => initAll();
In this case, an anonymous function is created that, when invoked, calls initAll() immediately. However, the reference of this outer function is still assigned to window.onload, so the event handler will wait for the load event to trigger the execution of both functions.
The above is the detailed content of JavaScript Function Calls: Empty Parentheses – Immediate Invocation or Reference Assignment?. For more information, please follow other related articles on the PHP Chinese website!