如何将变量传递给嵌套函数?

时间:2014-11-27 12:10:41

标签: javascript createjs

我最近开始使用createjs并且遇到了这个问题(它与createjs没什么关系):

for (a in ship.weapon) {

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

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

" a"按下按钮时的变量将是ship.weapon数组的长度。那我怎么做才能让#34; a"在click函数内部将保持for循环的值?

2 个答案:

答案 0 :(得分:4)

您可以使用闭包来冻结a

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
}

答案 1 :(得分:0)

你必须使用一个函数,没有别的办法。

function addEvent(a) {
   //code
   button[a].addEventListener("click", function() {
     ship.weapon[a].amount = ship.weapon[a].amount.plus(1);
   });
   //code
}

for (var a in ship.weapon) {
  addEvent(a);
}

这样可行。

相关问题