0
<script type="text/javascript">   
function buildList(list) {
  var result = [];
  for (var i = 0; i < list.length; i++) {
    var item = 'item' + list[i];
    result.push( function() {console.log(item + ' ' + list[i])} );
  }
  return result;
}

function testList() {
  var fnlist = buildList([1,2,3]);
  fnlist[0]();
}
testList(); 
</script>

问题:

在 firefox->console 中,它显示item3 undefined,为什么?

4

2 回答 2

0

你可以改变

result.push(function() {console.log(item + ' ' + list[i])} );

result.push(function() {console.log(item + ' ' + list[i] + ' ' + i)} );

然后你发现 i 是3,你应该使用 clousre 来避免这个问题。

于 2013-07-03T03:56:33.027 回答
0

这是因为闭包引用的评估发生在语句的执行时(item + ' ' + list[i] + ' ' + i,到那个时候值i变为4,这list[4]返回未定义。

执行顺序将是,您正在i循环中创建一个闭包变量,因此推送到result引用相同实例的所有函数引用i,对变量所做的任何修改都将反映在每个添加的函数中,无论何时添加.

这种情况下的解决方案是使用 iife 在循环语句内创建一个私有闭包

演示:小提琴

于 2013-07-03T04:02:21.307 回答