0

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?

2 Answers 2

3

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});                
}
Sign up to request clarification or add additional context in comments.

3 Comments

For learning purpose it's better not calling the closure parameter i as it's confusing. IMHO.
Thanks it works now :). Now another question what actually happens: (function(a))(b) means that b is passed as parameter .... oh wow now i got it myself: It's an anonymous function which is passed parameter b ?!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.