The other answer and comments are correct, index
in this case is just a function argument, but I'll (try) to explain a bit more what's going on here.
As others have said, index
is just a variable, in this case the argument to the function. There's nothing special about the name index
here, it could have been argument1
or vader
:-), or whatever.
So what's happening is that this function is being declared:
function(arg1){
g.children[i].onclick = function(){
alert(arg1) ;
}
}
I've replaced index
with arg1
to show that index
isn't special, although it works fine with index
. After that function's declared, it's being called by wrapping it in parens, and then passing the argument i
(the (i)
). This calls the function, assigning the current value of i
to the first argument to the function, arg1
here, or index
in the original. The function declares another function, this time
function() {alert(arg1);}
and assigns it to the onclick handler of the i'th
element of the g.children
array. So each onclick handler will be a function that just does an alert of the index of the array element.
If you step through the loop in a debugger, you'll see it effectively does:
g.children[0].onclick = function(){ alert(0); };
g.children[1].onclick = function(){ alert(1); };
g.children[2].onclick = function(){ alert(2); };
etc.