2014-11-27 5 views
0

는 최근 createjs을 사용하기 시작하고 (t은 createjs와 오도 무엇이든이 나던)이 문제에 온 :중첩 함수에 변수를 전달하는 방법은 무엇입니까?

for (a in ship.weapon) { 

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

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

은 "은"변수가 당연히 시점에 버튼이있을 누를 것을 우주선의 길이. 웨폰 배열. 그렇다면 클릭 함수 내부의 "a"가 for 루프의 값으로 유지되도록 어떻게 만들 수 있습니까?

답변

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 
} 
+0

감사합니다. – Vajura

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); 
} 

이렇게하면됩니다.

관련 문제