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

前端 未结 3 1876
醉话见心
醉话见心 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:08
    window.onload = foo;
    

    assigns the value of foo to the onload property of the window object.

    window.onload = foo();
    

    assigns the value returned by calling foo() to the onload property of the window object. Whether that value is from a return statement or not depends on foo, but it would make sense for it to return a function (which requires a return statement).

    When the load event occurs, if the value of window.onload is a function reference, then window's event handler will call it.

    0 讨论(0)
  • 2020-12-03 09:17

    Good answers, one more thing to add:

    Browser runtimes ignore non-object (string, number, true, false, undefined, null, NaN) values set to the DOM events such as window.onload. So if you write window.onload = 10 or any of the above mentioned value-types (including the hybrid string) the event will remain null.

    What is more funny that the event handlers will get any object type values, even window.onload = new Date is a pretty valid code that will prompt the current date when you log the window.onload. :) But sure nothing will happen when the window.load event fires.

    So, always assign a function to any event in JavaScript.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题