Search code examples
javascriptcreatejs

How do i pass a variable to a nested function?


I have recently started to use createjs and have come to this problem (which doesnt have anything t odo with createjs):

for (a in ship.weapon) {

    //code
    button[a].addEventListener("click", function() {

        ship.weapon[a].amount = ship.weapon[a].amount.plus(1);
    });
    //code
}

The "a" variable will ofcourse at the time that the button is pressed be the lenght of the ship.weapon array. So how do i make it so that the "a" inside the click function will stay at the value of the for loop when it was made?


Solution

  • You can use a closure to freeze the a value

    for (a in ship.weapon) {
    
        (function(index) {
            button[index].addEventListener("click", function() {
    
                ship.weapon[index].amount = ship.weapon[index].amount.plus(1);
            });
        })(a); // calls the function I just defined passing 'a' as parameter
    }