标签:style blog color io for ar div cti log
//函数作用域 function func(){ var arr = [1,3,5,7,9]; var sum = 0; for(var i = 0,len = arr.length;i < len;i ++){ sum += arr[i]; } console.log("%d\t\n%d",i,sum); } func(); //5 //25 //闭包特性 var outter = []; function clouseTest(){ var arr = ["one","two","three","four"]; for(var i = 0, len = arr.length;i < len;i ++){ var x = {}; 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(var i = 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="two", invoke=function()} //1 //4 //Object { no=0, text="one", invoke=function()} //0 //关于i输出的都是4的解释:因为,在每次迭代的时候这样的语句x.invoke=function(){console("%d",i);}并没有 //被执行,只是构建了一个函数体为“console.log("%d",i);”的函数对象,如此而已。而当i = 4时,迭代停止,外部函数返回 //当再去调用outter[i].invoke()时,i的值依旧为4,因此outter数组中的每一个元素的invoke都返回i的值为4. //引用 var obj = {};//空对象 var ref = obj;//引用 obj.name = "objectA";// console.log(ref.name);//ref跟着刚添加的name属性 obj = ["one","two","three","four"];//obj指向了另一个对象(数组对象) console.log(ref.name);//ref还指向原来的对象 console.log(obj.length);//3 console.log(ref.length);//undefined //objectA //objectA //3 //undefined
标签:style blog color io for ar div cti log
原文地址:http://www.cnblogs.com/xiaoxian1369/p/3938740.html