I'm new in JS and quite confused about the following code:
HTML
<button id="btn0">Click Me</button>
<button id="btn1">Click Me</button>
<button id="btn2">Click Me</button>
JS version 1
var test = {
clk: function () {
for (var i = 0; i < 3; i++) {
this.setup(i);
}
},
setup: function (data) {
var btn = document.getElementById("btn" + data);
btn.onclick = function () {
test.show(data);
}
},
show: function (data) {
alert(data);
}
}
test.clk();
If I run the program and click the 3 buttons, then they show each value of data they kept which are in turn 0, 1, 2
However, if I change the JS code to:
var test = {
clk: function () {
for (var i = 0; i < 3; i++) {
var btn = document.getElementById("btn" + i);
btn.onclick = function () {
test.show(i);
}
}
},
show: function (data) {
alert(data);
}
}
test.clk();
Run and click the 3 buttons, then all give the same result of 3
? how come the result of 3
? How come each does not give 0, 1, 2
? How is the JS version 1 different from the version 2?
I come from Java background, and all I thought was when the 3 buttons are clicked, all would give the result of 2
?