eclipse
eclipse

Reputation: 3011

Javascript giving parameters to inner function

So my basic setup is this:

for (var i = 0; i < 3; i++) {
    var indices = [-1, -1, -1];
    while (index == -1) {
        // Do Stuff
        index[i] = newIndex;  
    }       
    var press = function() { alert(i); };
    new control({press: press});                
}

Now when I press the each of the new controls instead of getting alert(0), alert(1) and alert(2) I get alert(3), alert(3) and alert(3). I can kind of understand whats going on. Now my question: how can i pass the different indexes to the function as I intended?

Upvotes: 0

Views: 48

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

It is because closure variable i, the solution is to create a private closure for each loop.

for (var i = 0; i < 3; i++) {
    var indices = [-1, -1, -1];
    while (index == -1) {
        // Do Stuff
        index[i] = newIndex;  
    }       
    var press = (function(myvar){
        return function() { alert(myvar); };
    })(i);
    new control({press: press});                
}

Upvotes: 3

gdoron
gdoron

Reputation: 150253

Use closure:

var press = (function (x) {
    return function () {
        alert(x);
    };
})(i);

This way the current i value is saved in a safe place, a private function.

Note that declaring variables (with var) inside loops are not standard, you should declare the press variable outside the loop.

Upvotes: 1

Related Questions