1 varnum = 2;//window.number=22 varobj = {3Num:4,//obj.number=44fn: (function () {5 This. num *= 2;//The self-executing function this is num of window, where window num=2*2=46num = num * 2;//Undefiend7 varnum = 3;8 return function () {9 This. Num *= 2;TenNum *= 3; One alert (num); A } - })(), -DB2:function () { the This. Num *= 2 - } - }; - + varfn =obj.fn1; -alert (num);//4 +FN ();//window.num=8 Popup 9 AObj.fn ();//obj.num=8 pop-up 9*3=27 at -alert (window.num);//8 -alert (obj.num);//8
Analyze the above code execution step by step:
Pre-interpretation under window:
var num; var obj; var fn;
Code Execution under window:
num=2;
obj=xxxfff000;
[Open up a heap of memory xxxfff000]
Num:4
fn: The return value of the self-executing function
Creating a private scope that does not destroy-a
pre-interpretation under a:
var num;
code Execution under a:
this.num*=2;//window.num=4
Num*=2;//num=undefined*2=nan
num=3;
return function () {.} xxxfff111
fn:function () {//parent scope is a
this.num*=2;
num*=3;
console.log (num);
} xxxfff111
Fn=obj.fn;//fn=xxxfff111
console.log (num);//4
fn ();
xxxfff111 () lines into a private scope
Pre-explanation: None
Code Execution:
this.num*=2;//window.num=8
num*=3;//Let the num=9 in the parent scope a
console.log (num);//9
Obj.fn ();
xxxfff111 () lines into a private scope
Pre-explanation: None
Code Execution:
this.num*=2;//obj.num=8
num*=3;//Let the num=27 in the parent scope a
console.log (num);//27
Console.log (window.num);//8
Console.log (obj.num);//8
JS learning closure, this keyword, pre-interpretation, scope synthesis