What is the difference between [removed] = init(); and [removed] = init;

前端 未结 3 1888
醉话见心
醉话见心 2020-12-03 08:26

From what I have gathered, the former assigns the actual value of whatever that functions return statement would be to the onload property, while the latter assigns the actu

3条回答
  •  广开言路
    2020-12-03 09:19

    window.onload = init();
    

    assigns the onload event to whatever is returned from the init function when it's executed. init will be executed immediately, (like, now, not when the window is done loading) and the result will be assigned to window.onload. It's unlikely you'd ever want this, but the following would be valid:

    function init() {
       var world = "World!";
       return function () {
          alert("Hello " + world);
       };
    }
    
    window.onload = init();
    

    window.onload = init;
    

    assigns the onload event to the function init. When the onload event fires, the init function will be run.

    function init() {
       var world = "World!";
       alert("Hello " + world);
    }
    
    window.onload = init;
    

提交回复
热议问题