2017-06-08 10 views
0

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 
生命維持がここで必要な理由、私は同じ結果と 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; 
}; 

一部の人がこれを説明できますか?私は何かが欠けていますか?

+1

また、 'for(let i'と書いてあれば、これ以上の最新の本を見つけることはできません。 –

答えて

0

私はそれがブログの間違いだと思います。 Closures Gone Awryセクションの最初の例が表示された場合は、idが関数として作成されます。しかし、最初のバグを解決しようとする2番目の例では、idがプロパティとして作成されています。

私は2番目の例が最初のものに似ているようにするべきだと思います。コード内のノートを注意してください、問題の生命維持や機能、このから離れて

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の消費の近くに、私はあなたが何かを欠落しているしていないと信じています。 idがプロパティである必要がある場合、コードは正しいです。

関連する問題