【问题标题】:Closure inside for loop, what is the inner IIFE for?for 循环内部的闭包,内部 IIFE 是做什么用的?
【发布时间】:2016-12-21 14:18:09
【问题描述】:

我一直在研究这篇关于闭包的文章:Understand Javascript Closures with Ease

最后一个示例处理 for 循环内的闭包。

我理解为什么使用 IIFE 将“i”的当前值捕获为“j”。我不明白这个例子是为什么在 return 语句周围有第二个内部 IIFE。 (我的评论在下面的代码中大写)。

没有内部 IIFE,代码似乎也能正常工作。 See CodePen here.

这个内部函数是出于某种原因需要,还是只是作者的疏忽?

function celebrityIDCreator (theCelebrities) {
var i;
var uniqueID = 100;
for (i = 0; i < theCelebrities.length; i++) {
    theCelebrities[i]["id"] = function (j)  { // the j parametric variable is the i passed in on invocation of this IIFE
        return function () {   //<--WHY DOES THIS INNER FUNCTION NEED TO BE HERE?
            return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct value to the array
        } () // BY adding () at the end of this function, we are executing it immediately and returning just the value of uniqueID + j, instead of returning a function.
    } (i); // immediately invoke the function passing the i variable as a parameter
}

return theCelebrities;
}

var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0},{name:"Willis", id:0}];

var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

var stalloneID = createIdForActionCelebs [0];
console.log(stalloneID.id); // 100

var cruiseID = createIdForActionCelebs [1];
console.log(cruiseID.id); // 101

var willisID = createIdForActionCelebs[2];
console.log(willisID.id); //102

【问题讨论】:

    标签: javascript


    【解决方案1】:

    正如您所观察到的,内部功能没有实际效果。使用它没有意义。

    这似乎是文章中上一个示例的保留,其中返回的是函数而不是数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多