3
我一直在關閉閉包中的這篇文章:Understand Javascript Closures with Ease封閉內循環,內部IIFE是什麼?
最後一個例子處理了for循環中的閉包。
我明白爲什麼使用IIFE將'i'的當前值捕獲爲'j'。我不明白這個例子是爲什麼有一個第二,內部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