JS闭包和函数参数

时间:2015-11-07 19:03:41

标签: javascript closures

以下代码片段来自JS和闭包上来自this线程的“示例5”。或者,this other thread类似于我对我的好奇。

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

function testList() {
    var fnlist = buildList([1,2,3]);
    for (var j = 0; j < fnlist.length; j++) {
        fnlist[j]();
    }
}

此片段来自的线程表示输出为:“item3 undefined”x3。我理解为什么“item3”被打印三次,但我不明白为什么list[i]未定义。

我的问题:因为list是buildList的参数,这是否意味着它不是result.push中匿名函数闭包的一部分?如果buildList(otherList)中有一个变量设置为list(并且匿名函数使用了otherList [i]),那么otherList [i]会在闭包中吗? (因此,而不是“item3 undefined”x3,输出将是“item3 3”x3)。

1 个答案:

答案 0 :(得分:0)

它有三个元素,因此最大有效索引为2.因此它不打印item3 undefined它是item2 undefined

原因:

由于您知道该函数每次都打印item-2字符串,因为该函数与引用有界,而不是值。 (使用立即调用函数可以避免这种情况。)

但是当我越过i < array.length 时,循环停止/停止,因此i的最后更新值现在是3和数组[1,2,3]在索引3处是undefined。因此,您看到了未定义的值。

<强>验证

添加console.log,如下所示

    for (var i = 0; i < list.length; i++) {
        var item = 'item' + i;
        result.push( function() {
             console.log(i);              //Prints 3 for all 3 invocation.
             alert(item + ' ' + list[i])
        } );
    }