0

I have executed below code snippet and got the output as follows (Side effect of closure?)

If I want to get id as 101,102 and 103, please let me know the corrective step.

<html>
<head>
<script language="JavaScript">
    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 celebID = createIdForActionCelebs [0];
    console.log(celebID.id()); // 103
    console.log(celebID); // Stallone
    celebID = createIdForActionCelebs [2];
    console.log(celebID.id()); // 103
    console.log(celebID); // Wills
</script>
</head>
<body> HI Closures</body>
</html>
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
  • As specified in comments with // ( String after // is my output) – Ravindra babu Jul 28 '15 at 17:56
  • While posting this question, some how I did not get http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example in previously posted questions. If I have found that one, I should not have posted this question – Ravindra babu Jul 28 '15 at 18:08
  • The solution in other question works now. Thanks Felix – Ravindra babu Jul 28 '15 at 18:27

0 Answers0