Look at the following code:
window.onload = someFunction;
Many times I see the use of this kind of code and even I use the same. But, there
In this case, you are registering a callback function for the window onload
event. To do so, you give a reference to the function, you don't execute the function (unless, of course, executing the function returns another function which is used as the callback handler). The function you specify will be executed when the onload
event occurs, that is, when the page finishes loading.
In JavaScript, parentheses do matter. In your case, you are assigning the function object itself to a certain slot of window
. When putting the parentheses, you explicitly call the function, thus the value of someFunction()
is the returned value of the function, not the function object itself. In short :
A special case is someVar = new someConstructor;
which should not be used generally, and does not follow my short explanation above. For a very good explanation of function, and that particular statement above, see the wonderful book by Douglas Crockford Javascript, the Good Parts.
You're not calling the function, you're telling the browser which function to call, onload.
Referencing a function and calling a function are never interchangeable: they're completely different things.
You may, however, call a function that returns a function:
function getFunction() {
return function() {
alert("I'm the real onload function.");
};
}
window.onload = getFunction();