//这是在浏览器环境下,chrome下 var n =2 ; var obj={ n:4, fn1:(function(){ console.log("fn1->this ="+this); //这里立即执行时,this是window console.log("fn1->this.n = "+this.n); //这里是2 this.n *=2; n = n*2; //这里的n是取下面没赋值的n,所以结果是nan,当变量在使用时还没赋值,但是下面有var语句包含这个变量,这时变量是undefiend console.log("fn1->n = "+n); //nan var n = 3; //这里n才赋值 return function() { this.n*=2; //这里是在下面fn1()调用时时执行,所以这里的this是window console.log("匿名函数里的this.n="+this.n); //8 n *=3; //这里取外层作用域的3 console.log("匿名函数里的n="+n); //9 } } )() } var fn1 = obj.fn1; console.log(obj.n); //4 console.log(n); //8 fn1(); console.log(n) //8 console.log(obj.n); //4
//node 环境下 var n =2 ; var obj={ n:4, fn1:(function(){ console.log("fn1->this ="+this); //这里的this是global对象 console.log("fn1->this.n = "+this.n); //global没有n,所以n是underfined this.n *=2; //这里是nan,因为n是undefined,所以乘以2是nan n = n*2; //同理下面才给n赋值这里的n*2是nan console.log("n=n*2,n is "+n); var n = 3; return function() { this.n*=2; console.log("匿名函数里的this.n="+this.n); //global没有n,所以这里是nan n *=3; console.log("匿名函数里的n="+n); //9 引用上面 var n=3 这里的3 } } )() } var fn1 = obj.fn1; console.log(obj.n); //4 console.log(n); //2 fn1(); console.log(n) //2 console.log(obj.n); //4