MeLight MeLight - 2 months ago 11
Javascript Question

Why can deep nested function access top level vars?

I've been doing some javascript reading, and I've gathered that a closure has access only to the closure "wrapping" it, or, you might say it's immediate parent. Now I've been playing a bit, and I see in this jsfiddle that even deep nested functions have access to to vars defined way up.

Can anyone please explain that? Or explain what have I got completely wrong?

http://jsfiddle.net/tPQ4s/

function runNums() {
this.topVar = 'blah';
return function(){
(function() {
(function() {
console.log(topVar);
})();
})();
}
}

var someFunc = runNums();
someFunc();

Answer

That is because the chain runs further up to the top context.
In the example, that would be:

window < runNums < anonymous < anonymous < anonymous

Variables living in any of these will be available in the last anonymous function. In runNums, only variables living in runNums or window will be available. In the first anonymous function, only its variables and those living in runNums or window will be available, etc.