JavaScript! [removed] = someFunction and [removed] = someFunction()

后端 未结 5 1595
逝去的感伤
逝去的感伤 2020-12-18 14:55

Is there a difference between:

  1. window.onload = someFunction;

  2. window.onload = someFunction();

Th

相关标签:
5条回答
  • 2020-12-18 15:20

    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)
    }
    
    0 讨论(0)
  • 2020-12-18 15:20

    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

    0 讨论(0)
  • 2020-12-18 15:23

    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);
    };
    
    0 讨论(0)
  • 2020-12-18 15:29

    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.

    0 讨论(0)
  • 2020-12-18 15:44

    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.

    0 讨论(0)
提交回复
热议问题