0

I am trying to execute the following code:

for (var i = 0; i <= 9; ++i) {
    State.prototype["button" + i.toString()] = function () {
        console.log("I am a digit button" + i.toString());
        this.setValue(i.toString());
    };
}

But it is wrong, because the i variable is common for all the function created. For example I want the function State.prototype.button0() to work as:

console.log("I am a digit button" + "0");
this.setValue("0");

How to do it?

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
maximus
  • 4,201
  • 15
  • 64
  • 117

1 Answers1

1

Pass it to a function, so that the value of i doesn't change:

for (var i = 0; i <= 9; ++i) {
    (function(i){
        State.prototype["button" + i.toString()] = function () {
            console.log("I am a digit button" + i.toString());
            this.setValue(i.toString());
        };
    })(i);
}
Matt Zeunert
  • 16,075
  • 6
  • 52
  • 78