Why does this closure-scoped variable lose its value?

戏子无情 提交于 2019-11-30 20:28:32

It's happening because this function:

(function( ) { a = b; var b; })( );

...assigns undefined to a. var takes effect as of the beginning of the scope in which it's written, not where it is in the step-by-step code. And when you declare a variable, its initial value is undefined. So the above written more explicitly, but with exactly the same functionality, looks like this:

(function( ) {
    var b = undefined;
    a = b;
})( );

Specifically, when execution enters an execution context, these things happen:

  1. A behind-the-scenes variable object is created for the execution context and put at the top of the scope chain (the chain of variable objects used to resolve unqualified references).
  2. Properties are created on that variable object for each var declared within the context, regardless of where the var statement is. The initial value of each variable is undefined. Initializers are not handled at this point.
  3. Properties are created on the variable object for each function declared (with a function declaration, not a function expression) within the context, regardless of where the function declaration is.
  4. The function declarations are processed and the results assigned to the properties for those functions.
  5. Execution continues with the first line of step-by-step code in the context. When a var statement with an initializer is encountered, it's processed as a simple assignment statement.

The variable object is the thing that makes closures work, too, by the way. More here, but basically, when a function is created it gets an enduring reference to all of the variable objects in the scope chain at that point. That's what it uses to look up the variables it closes over. This is important, because a closure doesn't only have an enduring reference to the variables it actually uses, but to all variables in-scope where it's defined, whether it uses them or not, which can have implications for the lifecycle of those variables.

A great explanation but the simple answer is that the "a" variable is not declared inside of the inner function. Therefore, it becomes global scope overtaking the value of the outer scope.

a = "undefined"; // global scope

var = 1; // relative to its scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!