easierbycode
11/29/2012 - 6:43 PM

emulate block scope

emulate block scope

// http://bit.ly/gettingclosure

for (var i = 1; i <= 3; i++) {
  (function(i){
    // All variables (including i)
    // are now scoped to this block
    
    // On click, alerts '1', '2' and '3'
    $elem.click(function() { alert(i); });
  })(i);
}

// another way

function makeAlert(i) {
  return function() {
    alert(i)
  }
}
for (var i = 1; i <= 3; i++) {  
  // On click, alerts '1', '2' and '3' :D
  $elem.click(makeAlert(i));
}

// otherwise, i is shared by all functions created in this loop.

for (var i = 1; i <= 3; i++) {  
  // On click, alerts '4', '4' and '4' :(
  $elem.click(function() { alert(i); });
}