3
私はクロージャに関するこの記事を通して取り組んでいます:Understand Javascript Closures with Easeforループ内のクロージャー、内部IIFEは何ですか?
最後の例はforループ内のクロージャを扱っています。
私は 'i'の現在の値を 'j'としてキャプチャするためにIIFEを使用する理由を理解しています。私がこの例について理解していないのは、return文のまわりに2番目の内部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