如何在闭包中引用局部变量? [英] How are local variables referenced in closures?

查看:150
本文介绍了如何在闭包中引用局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一篇文章(傻瓜JavaScript闭包),其中一个示例如下。

I am reading an article (JavaScript Closures for Dummies) and one of the examples is as follows.

function buildList(list) {
  var result = [];
  for (var i = 0; i < list.length; i++) {
    var item = 'item' + list[i];
    result.push( function() {alert(item + ' ' + list[i])} );
  }
  return result;
}

function testList() {
  var fnlist = buildList([1,2,3]);
  // using j only to help prevent confusion - could use i
  for (var j = 0; j < fnlist.length; j++) {
    fnlist[j]();
  }
}

testList();

当调用testList时,会显示一个item3 undefined的警告框。文章有这个解释:

When testList is called, an alert box that says "item3 undefined". The article has this explanation:


fnlist [j]()调用匿名函数时, 它们都使用相同的单个闭包,并且它们使用该闭包内的i和item的当前值(其中i的值为3,因为循环已完成,item的值为' item3')。

When the anonymous functions are called on the line fnlist[j](); they all use the same single closure, and they use the current value for i and item within that one closure (where i has a value of 3 because the loop had completed, and item has a value of 'item3').

为什么item的值为'item3'?当i变成3时,for循环结束吗?如果它的结束不应该项目仍然是'item2'?或者是当testList调用函数时再次创建的变量项。

Why does item have a value of 'item3'? Doesn't the for loop end when i becomes 3? If it ends shouldn't item still be 'item2'? Or is the variable item created again when testList calls the functions?

推荐答案

b
$ b

You're close...


为什么item的值为'item3'?当i变成3时,for循环结束吗?

Why does item have a value of 'item3'? Doesn't the for loop end when i becomes 3?

是的。


不应该是
'item2'吗?

If it ends shouldn't item still be 'item2'?

这个例子有点棘手。在循环的最后一次迭代期间, i 是2,但它引用 list 数组的第3个元素换句话说, item =='item'+ list [2] =='item3'

Nope. This example is a little tricky. During the last iteration of the loop, i is 2, but it references the 3rd element of the list array, which is 3. In other words, item == 'item' + list[2] == 'item3'

或者是当testList调用函数时再次创建的变量项?

Or is the variable item created again when testList calls the functions?

第一次。我想你刚才错过了 item [2] 的值为3。

No, you were almost right the first time. I think you just missed that item[2] has the value of 3.

这篇关于如何在闭包中引用局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆