Skip to content Skip to sidebar Skip to footer

JavaScript! Window.onload = SomeFunction And Window.onload = SomeFunction()

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 o

Solution 1:

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)
}

Solution 2:

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);
};

Solution 3:

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.


Solution 4:

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


Solution 5:

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.


Post a Comment for "JavaScript! Window.onload = SomeFunction And Window.onload = SomeFunction()"