useful closure pattern


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. // a common mistake, this will not work as expected
  2. for (i ...) {
  3. var div_id = divs[i].id;
  4. divs[i].onmouseover = function () {
  5. show_element_id(div_id);
  6. };
  7. }
  8.  
  9. // Instead use a function to wrap the actual
  10. // function call. This takes advantage of closures
  11. // to remember the div_id value.
  12. for (i ...) {
  13. var div_id = divs[i].id;
  14. divs[i].onmouseover = function (id) {
  15. return function () {
  16. show_element_id(id);
  17. };
  18. }(div_id);
  19. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.