首页 > 编程语言 > 详细

[Javascript] Function scope

时间:2014-12-17 20:33:07      阅读:239      评论:0      收藏:0      [点我收藏+]

We have code like: 

var numbers = [1,2,3];

for(var i in numbers){ 
    setTimeout(function(){console.log(numbers[i]); 
    }, 0);
}

//3
//3
//3

Note:

1. function block doesn‘t create scope!

2. setTimeout function run after all the other code finished.

 

Therefore, before setTimeout get run, for block already exec 3 times and i was set to 2. 

Once setTimeout get running, it prints out numbers[i] which is 3.

 

Now, we change the code to:

var numbers = [1,2,3];

for(var i  in  numbers){
   (function(){
       var j = i;
        setTimeout(function(){
           console.log(numbers[j]);
        }) 
   })();
}

//1
//2
//3

 

Note:

1. function does create new scope.

2. the (function(){})() run immedatly.

3. (function(){}) inside for block actually is closure which does remeber the local var value (in our case is var j).

 

[Javascript] Function scope

原文:http://www.cnblogs.com/Answer1215/p/4170111.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!