【发布时间】: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