轻松理解JavaScript闭包中的示例
最后一个例子是:轻松理解JavaScript闭包中的示例,javascript,closures,Javascript,Closures,最后一个例子是: 有人能解释一下吗?我错过了什么吗?我认为这是博客上的一个错误。如果您看到闭包出错部分的第一个示例,id被创建为一个函数。但是,在您所指的第二个示例中,它旨在解决第一个示例中的错误,id被创建为一个属性 我认为第二个例子应该是这样的,以便与第一个相似。注意代码中的注释,在所讨论的IIFE附近,以及id作为函数的消耗 功能庆典创造者(The Elebrities){ var i; var uniqueID=100; 对于(i=0;i
有人能解释一下吗?我错过了什么吗?我认为这是博客上的一个错误。如果您看到闭包出错部分的第一个示例,
id
被创建为一个函数。但是,在您所指的第二个示例中,它旨在解决第一个示例中的错误,id
被创建为一个属性
我认为第二个例子应该是这样的,以便与第一个相似。注意代码中的注释,在所讨论的IIFE附近,以及id
作为函数的消耗
功能庆典创造者(The Elebrities){
var i;
var uniqueID=100;
对于(i=0;i console.log(createIdForActionCelebs[1].id());//101注:使用as function
,如果您只是为(let i)编写,那么这些花招都不是必需的。也许是时候找一本更新的书了。
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
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;
};