closure usage in javascript

This is bad source all nodes are show "nodes.length-1" when you click any node

var add_the_handler = function (nodes){
 var i;
 for(i=0; i<nodes.length; i+=1){
  nodes[i].onclick = function(e){
   alert(i);
  }
 }
}

this is a good pattern compared to above function

var add_the_handler = function (nodes){
 var i;
 for(i=0; i<nodes.length; i+=1){
  nodes[i].onclick = function(i){
   return function(e){
    alert(i)
   };
  }(i)
 }
}

Comments

Popular posts from this blog

Project euler 169 found clue

Floyd-Warshall's algorithm