MeLight MeLight - 9 months ago 36
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?

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

var someFunc = runNums();

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download