how come calling window.init from a global init function doesn't cause an infinite recursion?

773 views Asked by At

So, how come this code doesn't loop infinitely?

window.init = function(){
    console.log("window.init")
}

function init(){
    console.log("init")
    window.init();
}

init();

jsfiddle: http://jsfiddle.net/FAt6C/

1

There are 1 answers

0
cHao On BEST ANSWER

Your code is set to run on load (see the boxes at the top left), which basically tells jsFiddle to wrap this code in a function that then is set as the onload handler. function init() is actually declared in the scope of that event handler, not in the window.

Even when you don't wrap the code, though, function declarations basically run as part of setting up the current scope, before the other stuff in that scope (ECMA-262, ยง10.5). So init is already in existence before you say window.init =..., and that assignment statement overwrites the broken init. Meaning if you set the wrapping to "no wrap" (regardless of location), you should only see "window.init" in the console.