In JavaScript, does it make a difference if I call a function with parentheses?

前端 未结 5 546
不知归路
不知归路 2020-11-22 02:13

I noticed a difference when calling a function with empty parentheses, or without any parentheses at all. However, I am not passing any arguments to the function so I wonder

5条回答
  •  灰色年华
    2020-11-22 02:52

    window.onload = initAll();
    

    This executes initAll() straight away and assigns the function's return value to window.onload. This is usually not what you want. initAll() would have to return a function for this to make sense.

    window.onload = initAll;
    

    this assigns the actual function to window.onload - this is possible because in JavaScript, as @Felix says, functions are first class objects - without executing it. initAll will be executed by the load event.

提交回复
热议问题