Search code examples
javascriptfunctionglobal-scope

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


What's the difference between

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

and

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

if any?


Solution

  • 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.