我正在閱讀這個tutualial javascriptissexy.com.我跟着直到最後一個例子。關於封閉和內部的一些問題IIFE
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() {
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
首先,我沒有看到一個IIFE,或者至少在語法我很熟悉,其中有將與領先的左側括號一個(function()...
。另外,
return function() {
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
}();
爲什麼這兩個returns
?如果這意味着一個IIFE不需要周圍的括號?另外,j
如何在i
前面的例子中立即增加到數組長度?關於訪問actionCelebs
參數的元素id
的行theCelebrities[i]["id"] = function (j) {
。爲什麼該屬性最初需要設置爲每個元素的0
。
先前的例子
// This example is explained in detail below (just after this code box).
function celebrityIDCreator (theCelebrities) {
var i;
var uniqueID = 100;
for (i = 0; i < theCelebrities.length; i++) {
theCelebrities[i]["id"] = function() {
return uniqueID + i;
}
}
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()); // 103
值的這裏,所有都設置爲103
「前面的例子」的問題是分配給id字段的函數是celebrityIDCreator函數中引用「i」的閉包。這就是爲什麼所有明星都會得到相同的ID。頂部的例子是正確的方法。它定義了一個工廠方法,它爲不同的名人返回不同的功能並執行分配ID的功能。 – nhahtdh 2014-12-08 04:54:09
你不需要如圖所示的循環中的內部函數,這是浪費代碼,性能和可讀性,什麼都不做。註釋掉內在的一切,一切工作都一樣。 – dandavis 2014-12-08 05:37:13
@dandavis你的意思是說這個'return函數(){return {0}返回uniqueID + j; // for循環的每次迭代都會將當前值i傳遞給此IIFE,並將正確的值保存到數組中 }();'可以變成簡單的'return uniqueID + j;'?謝謝參觀。 – 1252748 2014-12-08 05:53:43