tiny javascript closure question
for(var i=0,len=btns.length;i<len;i++){
(function(){
btns[i].addEventListener('c开发者_开发技巧lick',function(e){
console.log(i)
},false)
})(i)}}
Hello everyone, I'm recently learning Javascript. In the above code for understanding a bit of closure, you know, just set 3 buttons to log 3 different i
.
Unfortunately, it failed. I know that I didn't get the point of closures. Why? I immediately execute the function so that the i
in the listener's callback function won't share the same i
Hope someone can help~
You pass the i
variable to the function, but the function ignores the argument and just binds to the i
inside the function is the same variable as the one outside (because you specify an empty formal parameter list).
Therefore your loop has completed and increased the single i
shared between all the closures to 3
before you get a chance to push any of the buttons.
Rewrite function()
with function(i)
and it will have a better chance of working.
Try this where you actually declare a parameter for the function so that i
gets a local definition inside the function:
for(var i = 0, len = btns.length; i < len; i++) {
(function(i){
btns[i].addEventListener('click',function(e){
console.log(i);
},false);
})(i);
}
As you had it, you were passing i
as a parameter to the function, but not actually defining it as a parameter so the passed one was not being used. This is one reason why it's a bad idea to use the same name because these types of mistakes won't make a javascript error. I'd prefer this with a different name for the internal variable so there's no chance of confusion between the two:
for(var i = 0, len = btns.length; i < len; i++) {
(function(loopVar){
btns[loopVar].addEventListener('click',function(e){
console.log(loopVar);
},false);
})(i);
}
You can see this work here: http://jsfiddle.net/jfriend00/Hb5t3/
精彩评论