I am more of a C++/Java programmer and fairly new to Javascript. I have been reading Javascript the good parts book.In the chapter on Functions, the author cites and example of attaching an event listener to nodes in the DOM by doing the following
// When you click on a node, an alert box will display the ordinal of the node.
1 var add_the_handlers = function (nodes) {
2 var i;
3 for (i = 0; i < nodes.length; i += 1) {
4 nodes[i].onclick = function (i) {
5 return function (e) {
6 alert(e);
7 };
8 }(i);
9
10 };
The aim of the above function is to add an onclick event handler to all of the nodes in the DOM such that when anyone of the nodes is clicked it alerts the number assigned to it or its ordinal.
I am not able to understand lines 5 through 8. I understand that the function (the onclick = function(i)...) is immediately called with i as its argument. But how is this 'i' being passed to the function that is being returned ? How is 'e' getting the value of 'i' that is later being alerted?
I tried playing around with it and ran the following code in my browser
window.onclick = function(i){
return function(e){
console.log("Inner function called");
alert(e);
}
}(4);
I expected an alert window with the number 4 in it. Instead the alert window shows [object MouseEvent].
I would really appreciate if someone explained this to me. Thanks