简体   繁体   中英

Closures - Compilation vs Interpretation phase javascript

// Code Starts

var a = 10;
function outer() {
    function inner() {
        console.log(a);
        console.log(b);
    };
    var b = 20;
    return inner;
}
var innerFn = outer();
innerFn();

// Code Ends

My Question is:

In Closures, the function remembers the scope information from the time the function object is created (In the above case, in the compilation phase) but at that time the assignments (for a and b) haven't really happened. So, how are the values for variables a and b retained.

Please correct me if something is wrong in the above statement.

As you said in your first sentence, the closure remembers the scope information . That includes the references to the variables, which already will have been declared (or are declared at the same time as the function). It does not matter what values these variables have - they are evaluated when the variables are actually used when the closure is called.

You will notice that when you overwrite a after having created the closure in the outer() call, it will give you the new value of a when calling innerFn() . Closures do not remember the values from the time of their creation.

I believe the closure in this case is actually created when you return inner , not when you define the function inner . Until you create a reference to a function, the closure mechanism would have no meaning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM