Reputation: 17087
I am still fighting my battle against my low IQ :D This is the usual infamous cycle with closures:
function r(){
var a = [];
var i;
for(i=0;i<10;i++){
a[i]=(function(x){
return function(){return x;}
})(i);
return a;
}
This is quite clear to me now. In order to understand closures better, I played with the code and came up with:
function r(){
var a = [];
var i;
for(i=0;i<10;i++){
a[i] = (function(){
var x=i;
return function(){return x;}
})();
}
return a;
}
Is my code fully equivalent?
Merc.
Upvotes: 0
Views: 169
Reputation: 85546
I guess you didn't try them, the first one doesn't even work! Use firebug to test your code. Here is a version of the first example which actually doesn't give errors:
function r() {
var a = [];
var i;
for (i=0; i<10; i++) {
a[i] = (function (x) {
return function () {
return x;
}
})(i);
}
return a;
}
So, after adding the missing closing brace, they are equivalent, they build an array of functions that return the numbers from 0 to 9, they don't build an array of numbers from 0 to 9. So for example, calling r()[5]();
returns 5 (is the sixth element of the array).
Upvotes: 2
Reputation: 150080
Is my code fully equivalent?
Yes.
I find it slightly easier to read the second way, because it saves having to look to the end of the immediately-executed function to find out what's passed in as a parameter (not that that's a big problem with short functions like this), but the first way is more compact and probably more common so...
Upvotes: 2