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>