It's caused by JavaScript closures and the behavior of variables declared in a for loop in JavaScript. Because the argument n
is part of addHandler
's closure, n maintains it's value for the function instances declared inside of itself. It just so happens that your passing in i from a for loop in the global space.
Here is a fiddle showing that behavior.
If you were to do something to increment n
inside of addHandler
, you would see that it doesn't actually effect i
. Once again, this is because of closure, n
exists inside of addHandler
's closure and was merely populated by i
.
Here is a fiddle showing that behavior.
Because of closure, n
will exist for however long whatever is created inside of addHandler
(in this case some function references) exist.
I hope that makes sense. It's tricky to explain, I think.
EDIT: Here is an awesome explanation of JavaScript closures and how they work.