Created
October 21, 2011 02:03
-
-
Save VoQn/1302942 to your computer and use it in GitHub Desktop.
one of why hate javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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