Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript! window.onload = someFunction and window.onload = someFunction()

Tags:

javascript

Is there a difference between:

  1. window.onload = someFunction;

  2. 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?

like image 224
Navneet Saini Avatar asked Aug 04 '26 22:08

Navneet Saini


2 Answers

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)
}
like image 181
phtrivier Avatar answered Aug 06 '26 13:08

phtrivier


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);
};
like image 29
MMM Avatar answered Aug 06 '26 11:08

MMM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!