What's the difference between a javascript function as a property of window, a function defined with a name

104 views Asked by At

What's the difference between

function doStuff(){
    //do lots of fun stuff
}

and

window.doStuff = function(){
    //do lots of fun stuff
}

if any?

4

There are 4 answers

0
Tim Erickson On BEST ANSWER

The first will create a doStuff function property in whatever is the current scope context. If that is window (or no scope defined), then the result will be the same as the second in a browser context. If the current scope, though, is for example within another function, then only a locally available function will be created and the effect will not be the same as the bottom.

0
harsh On

There is no difference between these two as long as the first is declared in a global scope.

0
Barney On

The first will work out of browser contexts, where window isn't available. It also has a name (regardless of what variable or method key it's assigned to), which is useful for, among other things, stack traces and recursion.

The second won't work in, say, node.js (although global would). It doesn't have a name of it's own, which makes recursion difficult, as in the following example:

window.doStuff = function( i ){
    if( --i ){
        return window.doStuff();
    }

    return i;
}

If window.doStuff gets assigned something else, as follows…

window.doStuff = 'erg';

…then the above function breaks, because it's anonymous and can't reference itself — it's essentially lost.

Of course, there's nothing stopping you from doing both:

window.doStuff = function doStuff(){
    //do lots of fun stuff
}
0
Xardas On

There is no big difference if you declare function in global scope. Difference appears when scope of code, where you are declaring a function is not global. For example, inside another function:

function doGlobalStuff()
{
    function doStuff(){
    // do lots of fun stuff
    }
}

If you execute doGlobalStuff() function window object will contain doGlobalStuff() method, but there is no doStuff() method in there. However, this function will create method doStuff() in window object:

function doGlobalStuff()
{
    window.doStuff = function(){
    // do lots of fun stuff
    }
}

Search for variable and function scope for more info, like this: What is the scope of variables in JavaScript?