function first(){
var items = document.getElementsByTagName("li");
for(var x = 0; x < items.length; x++){
items[x].onclick = function() {
console.log(x);
}
}
}
function second(){
var items = document.getElementsByTagName("li");
for(var x = 0; x < items.length; x++){
(function(val) {
items[val].onclick = function() {
console.log(val);
}
})(x);
}
}
function third(){
var items = document.getElementsByTagName("li");
for(let x = 0; x < items.length; x++){
items[x].onclick = function() {
console.log(x);
}
}
}
There are 4 items in the list. The outputs of three functions:
first: 4 4 4 4
second: 0 1 2 3
third: 0 1 2 3
I can not understand the output of the third function. In the second function, each IIFE call creates a new function object and, therefore, a new variable, val. But in the third function there is a single copy of the variable x, then how is the output: 0 1 2 3
Please correct me if I am wrong.
source
share