4. Scope and Closure
@ Wu Qiong Adam (SINA)
Note: Before reading this section, read 1-3:
Http://www.bkjia.com/kf/201201/117897.html
Http://www.bkjia.com/kf/201201/117898.html
Http://www.bkjia.com/kf/201202/118315.html
Scope is a key concept in JS. Only by figuring out it can we figure out the Closure (Closure ). JavaScript: The Definitive Guide explains Scope clearly, while JavaScript: The Good Parts does not. The following uses this program as an example to describe Scope and Closure:
For a JS program, there is a Global Scope Object. The Global variables we define are actually attributes of this Object. In the main program body, you can use this to access the content of this object. This is only one Global Scope Object in the Scope Chain.
Run var Counter = function () {…} according to the following principles (){...} Then, the objects in the system are shown as follows:
Scope Principle 1: When the Counter function is defined, JS will save the currently valid Scope Chain in the function object for future reference.
Run var counter1 = new Counter. According to the following principle, the system object is shown as follows:
Scope Principle 2: When a function is executed, a new Scope Object is created and the function content is completely analyzed, add the parameters and local variables to the attributes of the new Scope Object, and use the new Scope Object as the last section of the Scope Chain to update the Scope Chain.
Scope Chain is used to query attributes later. If this Scope cannot be found, it will be checked in the parent Scope to guide Global Scope Object. In fact, it is also a Delegation, so maybe the Scope Object is also connected with _ proto?
Then the Counter content is executed, and the increment and getValue functions are defined and then returned to counter1. According to principle 1, the system object is shown as follows:
After var counter2 = new Counter is executed, the object becomes:
Seeing the above object model, I don't expect the output of the following code to be like this:
Counter1.increment ();
Document. writeln ("counter1:" + counter1.getValue ());
Document. writeln ("counter2:" + counter2.getValue ());
Originally, it would not interfere with each other!
Finally, we provide the closure definition. The internal function G of a function F can access the local variables and parameters defined by F. This is called closure, which is the basis for encapsulation in JS!
For ease of narration, we ignore some details about JS memory management in this section. The garbage collection and stack will be decomposed in the next section.