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

前端 未结 5 593
不知归路
不知归路 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 03:01

    Functions in javascript are first-class citizens, and as such, can be assigned to other variables or passed around as arguments.

    So, when you do

    window.onload = initAll;
    

    You are setting the onload property of the window object to reference the initAll function itself.

    When you do

    window.onload = initAll();
    

    You are setting the onload property to hold the return value of initAll, since it will execute in place on that line.

提交回复
热议问题