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;
};
并产生了相同的结果:
public function init()
{
parent::init();
$this->on(self::EVENT_AFTER_INSERT, [$this, 'exampleMethodHere']);
}
有人可以解释这个吗?我错过了什么吗?
答案 0 :(得分:1)
我认为这是博客上的一个错误。如果您看到 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
需要属性,那么您的代码是正确的。