简体   繁体   English

闭包-编译与解释阶段javascript

[英]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. 在Closures中,函数会记住从创建函数对象时起的作用域信息(在上述情况下,在编译阶段),但是那时(a和b)的分配尚未真正发生。 So, how are the values for variables a and b retained. 因此,如何保留变量a和b的值。

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() . 你会发现,当你覆盖a已经创造了关闭后outer()调用,它会给你的新价值a打电话时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 . 我相信在这种情况下,闭包实际上是在您返回inner时创建的,而不是在定义函数inner Until you create a reference to a function, the closure mechanism would have no meaning. 在创建对函数的引用之前,闭包机制将毫无意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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