Skip to content

Instantly share code, notes, and snippets.

@VoQn
Created October 21, 2011 02:03
Show Gist options
  • Save VoQn/1302942 to your computer and use it in GitHub Desktop.
Save VoQn/1302942 to your computer and use it in GitHub Desktop.
one of why hate javascript
var buttons = document.querySelectorAll('button');
// fool
for (var i = 0, l = buttons.length; i < l; i++){
buttons[i].onclick = function(){
alert(i); // always alert buttons length. not inclemental.
};
}
// should
for (var i = 0, l = buttons.length; i < l; i++){
buttons[i].onclick = (function(n){
var m = n; // create new scope
return function(){
alert(m); // inclemental.
}
})(i);
}
// Do you not believe yet ? Try run this code, and click any link
var a = document.querySelectorAll('a');
for (var i=0,l=a.length; i<l; i++){
a[i].onclick=function(){
alert(i);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment