http://javascriptissexy.com/understand-javascript-closures-with-ease/ 的最后一个例子是:
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
console.log(createIdForActionCelebs[1].id); // 101
我不明白为什么这里需要 IIFE,我替换了 celebrityIDCreator
并产生了相同的结果:
var celebrityIDCreator = function(theCelebrities) {
var i;
var uniqueID = 100;
for (i = 0; i < theCelebrities.length; i++) {
theCelebrities[i]["id"] = function (j) {
return uniqueID + j;
// return function () {
// } () ;
} (i);
}
return theCelebrities;
};
有人可以解释一下吗?我错过了什么吗?
最佳答案
我认为这是博客上的一个错误。如果您看到 Closures Gone Awry 部分的第一个示例,id
是作为函数创建的。但是,在您所指的第二个示例中,该示例旨在解决第一个示例中的错误,id
被创建为属性。
我认为第二个例子应该是这样的,以便使其与第一个例子相似。请注意代码中的注释,靠近相关 IIFE 以及将 id
作为函数使用
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
} // NOTE. Not an IIFE
}(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 NOTE: Use as function
console.log(createIdForActionCelebs[1].id()); // 101 NOTE: Use as function
除此之外,我相信您不会错过任何东西。如果 id
需要是一个属性,您的代码是正确的。
关于javascript - 轻松理解 JavaScript 闭包中的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44425822/