I'm trying to learn Javascript closures. I'm having trouble getting my head around the fact that when you create several closures in a loop, all closures save only the last state of a variable. With this example
var links = document.getElementsByTagName('a');
for (var x=0; x<links.length; x++) attachListener();
function attachListener() {
links[x].addEventListener('click', function(){
console.log(x);
}, false);
};
When I have three links in my document, clicking on any link shows "3", I guess because x got incremented to 3 after the final run of the loop. I read in this excellent intro that if you run the outer function multiple times a new closure's created each time. So how come each closure doesn't save a different value for x each time I call the outer function?
When you pass x as a parameter to the outer function it does work as expected.
var links = document.getElementsByTagName('a');
for (x=0; x<links.length; x++) attachListener(x);
function attachListener(z) {
links[z].addEventListener('click', function(){
console.log(z);
}, false);
};
Now you get 0 when you click the first link, 1 on the second etc.
Can anyone please explain why there is this difference?
Cheers