Difference between assigning event handler to method with and without parentheses

Assuming you have the following:

function doStuff() {
//code
}

  • What version of IE doesn't pass the event as argument to listeners?
  • jQuery: more than one handler for same event
  • Can I change the event queue priority in JavaScript?
  • Bind load-event to iframe or run function if the load-event already fired
  • Find Elements With Events Attached
  • How can I capture the right-click event in JavaScript?
  • What is the the difference between the 2 statements ?

    window.onload = doStuff;

    window.onload = doStuff();

    Both statements immediately called the method, but if I used the first statement, I could treat onload as a function pointer to “doStuff” and just call the method again using:

    onload();

    Is this the only difference, and in general, is this all guaranteed behavior for event handlers ?

  • call functions within event handler
  • What is the event precedence in JavaScript?
  • How to use a function that takes arguments with jQuery's change() method?
  • Will this use of jQuery slow page display times?
  • Javascript: how to prevent keypress used to dismiss alert from triggering key event handler
  • Which JS event is fired when Chrome gets the download file?
  • 3 Solutions collect form web for “Difference between assigning event handler to method with and without parentheses”

    You’re actually a bit off in your understanding.

    window.onload = doStuff;
    

    means that when the onload event is triggered, the doStuff function will be called.

    window.onload = doStuff();
    

    means that when that line of code is reached (before the onload event is triggered), doStuff is executed and it’s return result is assigned to the onload handler.

    You probably want the first one unless doStuff returns a function to be executed when the onload event is triggered.

    window.onload = doStuff();
    

    This will fire immediately as the iterpreter get there.

    window.onload = doStuff;
    

    it’s a reference to a function which future to be called.

    Question :

    When should I use window.onload = doStuff();

    Answer:

    When you need to create closure :

    Example :

    window.onload = doStuff();
    

    Where

    function doStuff()
        {
            var i = 0;
            return function ()
            {
                return i++;
            };
        }
    
    window.onload = doStuff();
    

    This executes doStuff() in straight away and assigns the function’s return value to window.onload

    window.onload = doStuff;
    

    This assigns the actual function to window.onload. It assign it without executing it. doStuff will be executed when you call the load event.