Chapter 7 Closures and Variables Question
On page 188 there is the following code:
function createFunctions(){
var result = new Array();
for (var i=0; i < 10; i++){
result[i] = function(){
return i;
};
}
return result;
}
The explanation paragraph that follows is confusing, it states the following:
'This function returns an array of functions. It seems that each function should just return the value of its index, so the function in position 0 returns, the function in position 1 returns 1, and so on. In reality, every function returns 10.'
The first part makes sense in that the function returns an array of functions, but as far as each index holding 10 is concerned it doesn't actually hold do that. I tried calling the function to see what value each actually holds like so:
var theResult = createFunctions();
alert(theResult);
The value you get is the actual function itself for each index not the value of 10 for each index that is allegedly supposed to be return, I tried running the eval() method on the theResult variable instead but the result was the same. So what is actually going on? Have I missed something here?
Also with the so called solution to the problem the same thing happens, solution in book as follows:
function createFunctions(){
var result = new Array();
for (var i=0; i < 10; i++){
result[i] = function(num){
return function(){
return num;
};
}(i);
}
return result;
}
Also how is num actually getting the i variable, is it due to the line }(i); as that is the final variable within the enclosure of the containing function?
Finally how is the the anonymous function being called immediately as stated in the book, what line is actually calling it?
The book so far has been excellent but this specific section of closures and variables has confused the heck out of me.
Please help.
Thanks
