scope - Why does one JavaScript closure work and the other doesn't? -
It is believed that when the user clicks on the first link, it will "1", and the second link will warn,
"2", etc.:
Version 1:
& lt; A href = "#" id = "link1" & gt; Click me & lt; / A & gt; & Lt; A href = "#" id = "link2" & gt; Click me & lt; / A & gt; & Lt; A href = "#" id = "link3" & gt; Click me & lt; / A & gt; & Lt; A href = "#" id = "link4" & gt; Click me & lt; / A & gt; & Lt; A href = "#" id = "link5" & gt; Click me & lt; / A & gt; & Lt; Script type = "text / javascript" & gt; (I = 1; i & lt; = 5; i ++) {document.getElementById ('link' + i) .click = (function () {return function () {var n = i; alert (n); Return false;}}) (); } & Lt; / Script & gt;
Version 2:
& lt; A href = "#" id = "link1" & gt; Click me & lt; / A & gt; & Lt; A href = "#" id = "link2" & gt; Click me & lt; / A & gt; & Lt; A href = "#" id = "link3" & gt; Click me & lt; / A & gt; & Lt; A href = "#" id = "link4" & gt; Click me & lt; / A & gt; & Lt; A href = "#" id = "link5" & gt; Click me & lt; / A & gt; & Lt; Script type = "text / javascript" & gt; (I = 1; i & lt; = 5; i ++) {document.getElementById ('link' + i) .click = (function () {var n = i; return function () {warning (n); Return false;}}) (); } & Lt; / Script & gt; Version 1 will not work version 2 I think I know the reason, but compare with other people's explanation as Version 1 does not work. Version 1 does not work because in this case a common variable "i" (a
), because you var
) that are shared by each "click" handler function, loop creates. In the second edition, you create a new lexical scope with small cover function. It gives each "click" handler, it is very personal "i".
Comments
Post a Comment