首页 > 代码库 > [Javascript] Function scope
[Javascript] Function scope
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。