How does a function in a loop (which returns another function) work?

Viewed 15856

I've been trying to assign a function to onclick event of a dynamically created "a" tag in JavaScript. All of the tags are created in a loop as follows:

for ( var i = 0; i < 4; i++ )
{
  var a = document.createElement( "a" );
  a.onclick = function( ) { alert( i ) };
  document.getElementById( "foo" ).appendChild( a );
}

The alerted value for all four links is always "4". Pretty obvious. When googling I came across a post that shows the following code snippet:

a.onclick = (function(p, d) {
return function(){ show_photo(p, d) }
})(path, description);

I managed to tweak it for my needs and got the alert( i ) thing to work correctly but I'll appreciate if someone could explain exactly what the above code does.

3 Answers
Related