Return to Snippet

Revision: 2906
at May 3, 2007 13:55 by voidlock


Updated Code
// a common mistake, this will not work as expected
for (i ...) {
   var div_id = divs[i].id;
   divs[i].onmouseover = function () {
       show_element_id(div_id);
   };
}

// Instead use a function to wrap the actual
// function call.  This takes advantage of closures
// to remember the div_id value.
for (i ...) {
   var div_id = divs[i].id;
   divs[i].onmouseover = function (id) {
       return function () {
           show_element_id(id);
       };
   }(div_id);
}

Revision: 2905
at May 3, 2007 13:52 by voidlock


Initial Code
// a common mistake, this will not work as expected
for (i ...) {
   var div_id = divs[i].id;
   divs[i].onmouseover = function () {
       show_element_id(div_id);
   };
}

// Instead use a function to wrap the actual
// function call.  This takes advantage of closures
// to remember the div_id value.
for (i ...) {
   var div_id = divs[i].id;
   divs[i].onmouseover = function (id) {
       return function () {
           show_element_id(id);
       };
   }(div_id);
}

Initial URL


Initial Description


Initial Title
useful closure pattern

Initial Tags
javascript, textmate

Initial Language
JavaScript