An exercise on the scope of functions in which this refers and closures
- Javascript code
var x = 3,
obj = {x: 5};
obj.fn = (function(){
this.x *= ++x;
return function(y){
this.x *= (++x)+y;
console.log(x);
}
})();
var fn = obj.fn;
obj.fn(6);
fn(4);
console.log(obj.x, x);
Copy the code
- Text parsing:
- The first step is for the browser to create a stack of memory (ECStack) for code execution
- Form the global context (EC(G)), declare and define the global variable x, the initial value is 3; Declare and define the global variable obj with an initial value of object {x: 5}.
- Creates the self-executing function (0x002) and assigns the result of the function to the property fn of the obj object
- X = window.x * (++window.x) = 12 (the value of the global variable x is changed to 12)
- Create a new anonymous function (0x003) in the self-executing function and assign the address of the function to the fn property of obj; Obj. fn = function(y){this.x *= (++x)+y; console.log(x)}
- The code in the global context proceeds, assigning the heap address pointed to by the property FN of the obj object to the global variable FN, which is also a function.
- * this. X *= (++x)+y; * this. Console. log(x) “, this refers to obj, and the x in ++x does not exist in the current private context, so search up and find the global variable x (value 12), y is the current private context of the private variable value of parameter 6. So get: obj. X = obj. X * (+ + window. X + y) = 5 * (+ + 12 + 6) = 95. Finally ==obj. X = 95==
Function fn executes ((0x003)), forms a private context, and still executes the code: “this.x *= (++x)+y; Console. log(x) “, this refers to the window, and the x in ++x does not exist in the current private context, so we can look up and find the global variable x. Y is the private variable in the current private context with the value of parameter 4, so: X *((++window.x) + 4) = 13 *(14 + 4) = 234, that is, ==window.x = 234== console.log(obj.x, x); Output 95, 234 in turn
- Chapter ONE Illustrating the Truth