Skip to content Skip to sidebar Skip to footer

Difference Between Assigning Event Handler To Method With And Without Parentheses

Assuming you have the following: function doStuff() { //code } What is the the difference between the 2 statements ? window.onload = doStuff; window.onload = doStuff(); Both stat

Solution 1:

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++;
        };
    }

Solution 2:

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.


Post a Comment for "Difference Between Assigning Event Handler To Method With And Without Parentheses"