Sample Code
1 var xxxVar1 = 1;
2 var outer = function (){
3 var xxxVar2 = 2;
4
5 var results = [];
6
7 for (var I = 0; I <3; I ++)
8 {
9 var inner = function (){
10 var xxxVar3 = 3;
11 return xxxVar3 + xxxVar2 + xxxVar1 + I;
12}
13 results. push (inner );
14}
15
16 return results;
17}
18
19 var xxxVar1 = 100;
20 var xxxVar2 = 200;
21 var xxxVar3 = 300;
22 var results = outer ();
23 results [0] ();
24 results [1] ();
25 results [2] (); execution result
Many people may know the execution results of the above example, but not all of them understand why, including myself. Glossary • Activity object: When the callback function is called, The javascript interpreter collects all local variables (variables declared in var form) in the function body ), store these local variables in an object called an activity object. All the variables are initially undefined.
Sample Code
1 var fun = function (){
2 alert (name );
3 var name = 'duan Guangwei ';
4} when this function is executed (fun (), the function body has not been executed, and the current activity object is [{name: undefined}], so fun () the execution result is:
• [Scope] attribute of a function: each function is assigned a [scope] attribute during definition (when a function instance is generated). This attribute points to the current "scope chain ". Developers cannot access this property, and only javascript can access it.
• Scope chain: When a function is called, the javascript engine maintains a scope chain for this call, this scope chain is the scope chain pointed to by the function [scope] plus the activity object when the function is called, in the form of [activity object, the scope chain when the function is defined].
Sample Code
1 var a = 1;
2 // Step 1: [{a: 1, outer: undefined}]
3
4 var outer = function (){
5 // Step 3: [{B: undefined, inner: undefined}, {a: 1, outer: function}]
6 var B = 2;
7 var inner = function (){
8 // Step 5: [{}, {B: 2, inner: function}, {a: 1, outer: function}]
9 return a + B;
10}
11
12 // Step 4: [{B: 2, inner: function}, {a: 1, outer: function}]
13 return inner ();
14}
15
16 // Step 2: [{a: 1, outer: function}]
17 outer (); rule 1javascript of the scope chain generally runs in a certain host. Each host provides a "global object" or "global activity object ", this global object is the root node of all scope chains.
Rule 2 "value operation" (for example, alert (xxxVar) is used to search for variables named "xxxVar" along the scope chain, and return the first value found, if not, an exception is thrown (ReferenceError: xxxVar is not defined ).
Rule 3 the "value assignment operation" (for example, xxxVar = 'duan Guangwei ') rule is to search for variables named "xxxVar" in sequence along the scope chain and overwrite the values found in the first query, if not, add "xxxVar" to the global object.