Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on May 19th, 2012  |  syntax: JavaScript  |  size: 1.22 KB  |  views: 101  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="iso-8859-1">
  5. <script src="lib/jquery-1.7.2.js"></script>
  6. <title>The good and the bad closures in JavaScript</title>
  7. <script>
  8. $(function () {
  9.     init_page_bad_closure('testbed1');
  10.     init_page_good_closure('testbed2');
  11. });
  12.  
  13. function init_page_bad_closure (id) {
  14.     var div = $('#'+id);
  15.     for (var i=1; i < 5; ++i) {
  16.         var link = $('<a href="#">Link '+id+' #'+i+'</a>');
  17.         var please_enclose_my_i = i;
  18.         link.click(function(){
  19.             alert("Click "+id+" "+please_enclose_my_i);
  20.             please_enclose_my_i++;
  21.         });
  22.         div.append(link).append('<br>');
  23.     }
  24.     div.append('<br>');
  25. }
  26.  
  27. function init_page_good_closure (id) {
  28.     var div = $('#'+id);
  29.     for (var i=1; i < 5; ++i) {
  30.         (function (my_personal_i) {
  31.             var link = $('<a href="#">Link '+id+' #'+my_personal_i+'</a>');
  32.             link.click(function(){
  33.                 alert("Click "+id+" "+my_personal_i);
  34.                 my_personal_i++;
  35.             });
  36.             div.append(link).append('<br>');
  37.         })(i);
  38.     }
  39.     div.append('<br>');
  40. }
  41.  
  42. </script>
  43. </head>
  44. <body>
  45. <div id="testbed1"></div>
  46. <div id="testbed2"></div>
  47. </body>
  48. </html>
clone this paste RAW Paste Data