【发布时间】:2015-07-16 07:27:59
【问题描述】:
所以我已经在 SO 上学到了很多关于闭包的知识。
但我还是找到了一个我无法向自己解释的例子:
function buildList(list){
var result = [];
for(var i = 0; i < list.length; i++) {
var item = "item: " + list[i] + " i's value: " + i; //i has the value of 2 here, but why?
result.push( function(){document.write(item + ", list[i]:" + list[i] + ", i's value in the anonymous function:" + i + "<br>")});
} //i = 3 here
return result;
}
function testList(){
var testTheList = buildList([1,2,3]);
for (var j = 0; j < testTheList.length; j++) {
testTheList[j]();
}
}
testList();
正如我所期望的那样,当我执行 testList() 时,我应该是 3。
但结果是:
item: 3 i's value: 2, list[i]:undefined, i's value in the anonymous function:3
item: 3 i's value: 2, list[i]:undefined, i's value in the anonymous function:3
item: 3 i's value: 2, list[i]:undefined, i's value in the anonymous function:3
为什么是 i 用于 var item => 2 和 i 在匿名函数 => 3 中?正如我所读到的,闭包创建了新的执行环境,但我不应该为闭包提供相同的值吗?
编辑
这不是JavaScript closure inside loops – simple practical example的重复,我不想知道,如何创建一个新的执行环境。
我想知道为什么同一个变量 i(循环的)的值在同一个作用域内不同?
【问题讨论】:
标签: javascript closures