closure3
http://javascriptissexy.com/understand-javascript-closures-with-ease/
by shenoyvnm
JavaScript
/**
theCelebrities[i][“id”] = function (j) {
Im not familiar with the above syntax. Could you please explain?
answer---
This statement assigns a new value to a variable inside an array of objects.
Recall that theCelebrities now has the value of [{name:”Stallone”, id:0}, {name:”Cruise”, id:0}, {name:”Willis”, id:0}]
The first set of square brackets, theCelebrities[i], calls an object by its array position. If i = 0 then theCelebreties[i] is equal to the first object in the array, in this case, {name:”Stallone”, id:0}.
The second set of brackets, [“id”], call that object’s property by its name “id” .
The rest of the statement “= function(j){….}(i)” simply reassigns the value of the property “id” from “0” to the return of the function.
On the macro level {name:”Stallone”, id:0} becomes {name:”Stallone”, id:100}.
This type of index referencing works with any type of nested array:
if a = [4, [apple, 7, triangle, [88, 69], 6, 6], tomorrow] then:
a[1][3][0] is equal to 88; and
a[2] is equal to tomorrow;
Hope that helps ;)
**/
/** when debugging, see debuggers where i have set..its imp:-)
**/
function celebrityIdCreator(theCelebrities)
{
var i;
var uniqueId=100;
for(i=0;i<theCelebrities.length;i++)
{
debugger;
theCelebrities[i]["id"]=function(){
debugger;
return uniqueId+i;
}
}
return theCelebrities;
}
var celebrityIds=[{name:"raju",id:0},{name:"mahesh",id:0}];
var createIdForActionCelebs =celebrityIdCreator(celebrityIds);
debugger;
var stalloneID = createIdForActionCelebs[0];
console.log(stalloneID.id()); // 103