Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
like image 914
MeLight Avatar asked Dec 17 '22 05:12

MeLight


1 Answers

Without going too deep into the details, a closure technically describes a array like variable within the such called Activation Object that is handled from the javascript engine. An ActivationObject contains Variables declared by var, function declarations and formal parameters.

That means, anytime a new function (-context) is invoked, internally a new Activation Object is created. That object is part of the new Execution Context, a typicall EC looks like:

  • this context variable
  • Activation Object
  • [[Scope]]

The interesting part here is [[Scope]]. That variable contains all Activation Objects of all parent context and is filled when the EC is called. So now, when a function wants to access a variable, the name resolution process first looks into its own Activation Object, if nothing is found the search continues in the "Scope chain", which is just an Indexed search through our [[Scope]] variable (which again, is an array of parent contexts). Thats why we also speak a lot about "lexical scope" in ECMA-/Javascript.

Note: The above behavior is not described entirely, that would need several pages of text. Also it describes the ECMAscript3 262 specification. Things work a little different in ES5, but its still around the same thing

like image 181
jAndy Avatar answered Dec 18 '22 19:12

jAndy