Skip to content

Instantly share code, notes, and snippets.

@solominh
Created January 22, 2017 17:25
Show Gist options
  • Select an option

  • Save solominh/9fef12ad517b664936a1160a8c3519d4 to your computer and use it in GitHub Desktop.

Select an option

Save solominh/9fef12ad517b664936a1160a8c3519d4 to your computer and use it in GitHub Desktop.
<html>
<body>
<ul id="item-list">
<li>Item1</li>
<li>Item2</li>
<li>Item3</li>
<li>Item4</li>
<li>Item5</li>
</ul>
<script>
items = document.getElementsByTagName('li');
console.dir(items);
function test1() {
// Fail => alert(i) => trap variable i => variable i are the only one memory
for (var i = 0; i < items.length; i++) {
items[i].onclick = function () {
alert(i);
}
}
}
function test2() {
// ES6: Success => let j => block scope => items.length block scope
// => items.length j memory
for (var i = 0; i < items.length; i++) {
let j = i;
items[i].onclick = function () {
alert(j);
}
}
}
function test3() {
// ES6: same as above but shorter => never use var again
for (let i = 0; i < items.length; i++) {
items[i].onclick = function () {
alert(i);
}
}
}
function test4() {
// ES5: Use closures
for (var i = 0; i < items.length; i++) {
(function () {
var j = i;
items[i].onclick = function () {
alert(j);
}
})();
}
}
function test5() {
// ES5: Same as test 4 but cleaner
for (var i = 0; i < items.length; i++) {
(function (j) {
items[i].onclick = function () {
alert(j);
}
})(i);
}
}
test3();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment