2

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?

ipkiss
  • 13,311
  • 33
  • 88
  • 123
  • 1
    See the linked question and its answers, the concept involved is "closures." And/or see my own modest effort on my blog: [*Closures are not complicated*](http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html). – T.J. Crowder Jul 09 '16 at 08:58
  • This question and its answers are also relevant and useful [*JavaScript closure inside loops – simple practical example*](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – T.J. Crowder Jul 09 '16 at 09:00

0 Answers0