Reputation: 944
Is there a difference between:
window.onload = someFunction;
window.onload = someFunction();
The parentheses at the end. Do they make any difference?
We generally use the first one! What if we Have to pass some parameter to the function. How will we do it by using the first statement?
Upvotes: 3
Views: 15633
Reputation: 13361
As explained otherwise, the first form
window.onload = someFunction
Simply set the "onload" variable to be equals to the "someFunction" function ; when the page finishes loading, this function is called.
The other form :
window.onload = someFunction()
Sets the "onload" variable to be the result of calling someFunction. Unless "someFunction" itself returns a function, this is probably not what you want to do.
By default, the onload function is called with a single "event" argument. If you want to pass arguments, you might be able to do something like this :
window.onload = function (event) {
someFunction(someArg, someOtherArg)
}
Upvotes: 7
Reputation: 7310
Your second statement assigns the result of someFunction()
to window.onload
.
If you want to add a parameter, you can do the following:
window.onload = function () {
someFunction(parameter);
};
Upvotes: 4
Reputation: 943515
window.onload = someFunction;
assigns a function to onload
.
window.onload = someFunction();
calls a function and assigns its return value to onload
. (This is not desirable unless the return value of that function is another function).
What if we Have to pass some parameter to the function
Usually you define a new function which does nothing except call the original function with some arguments, then you assign the new function to the event handler.
Upvotes: 3
Reputation: 2619
Yes. If you put window.onload = someFunction()
it is expected that the result of someFunction()
is another function. This could be used for wrapping a function, or passing parameters. For instance:
window.onload = myFunction(arg1, arg2)
myFunction(arg1, arg2)
would be expected to return some function incorporating these two variables.
Upvotes: 0
Reputation: 6229
if you use
window.onload = someFunction;
a function with the name of someFunction is called on window.onload
if you use
window.onload = someFunction();
someFunction() runs and the result is assigned to window.onload
Upvotes: 1