//function Scope functionfunc () {vararr = [1,3,5,7,9]; varsum = 0; for(vari = 0,len = Arr.length;i < Len;i + +) {sum+=Arr[i]; } console.log ("%d\t\n%d", i,sum); } func (); //5 // - //Closure Characteristics varOutter = []; functionclousetest () {vararr = ["One", "one", "three", "four"]; for(vari = 0, Len = arr.length;i < Len;i + +){ varx = {}; X.no=i; X.text=Arr[i]; X.invoke=function() {Console.log ("%d\t\n%o\t\n%d\t\n", I, This, This. No); }; Outter.push (x); }} clousetest (); for(vari = Outter.length-1;i >= 0;i--) {Outter[i].invoke (); } //4 //Object {no=3, text= "Four", Invoke=function ()} //3 //4 //Object {no=2, text= "three", Invoke=function ()} //2 //4 //Object {no=1, text= "a", Invoke=function ()} //1 //4 //Object {no=0, text= "One", Invoke=function ()} //0 //The 4 interpretation of the I output is: because, at each iteration, such statements x.invoke=function () {Console ("%d", I);} And no //is executed, just constructs a function body for "console.log ("%d ", I);" Function object, that's all. And when i = 4 o'clock, the iteration stops, and the external function returns //When you call Outter[i].invoke () again, the value of I is still 4, so the invoke of each element in the Outter array returns the value of I as 4. //References varobj = {};//Empty Object varref = obj;//ReferencesObj.name = "Objecta";//Console.log (Ref.name);//ref follows the Name property you just addedobj = ["One", "one", "three", "four"];//obj points to another object (array object)Console.log (Ref.name);//ref also points to the original objectConsole.log (obj.length);//3Console.log (ref.length);//undefined //objecta //objecta //3 //undefined
JS scopes and closures--examples