2012-04-15 2 views
1

JS에서 게임을 만들면서 놀고있었습니다. 그리고 메인 html 파일의 이벤트에서 변수를 변경할 수없는 벽돌 벽을 치십시오. 즉 offSetX를 말합니다. 왜 변하지 않는거야?Cant '가 바깥 이벤트에서 객체 변수를 변경합니다.

var game = new Game(); 
window.addEventListener("keyup", game.input); 
game.start('myCanvas'); 

게임 개체는 다음과 같습니다.

function Game() { 

this.offSetX = 0; 

this.init = function (id) { 

    this.canvas = document.getElementById(id); 
    this.context = this.canvas.getContext('2d'); 
    this.blocks = []; 
    this.blocks.push(new block()); 

}; 

this.logic = function() { 
    for (var i in this.blocks) { 
     this.blocks[i].update(this.offSetX); 
    } 
}; 

this.draw = function() { 
    for (var i in this.blocks) { 
     this.blocks[i].draw(this.context); 
    } 
}; 

this.main = function() { 
    this.logic(); 
    this.draw(); 
    console.log(this.offSetX); 
}; 
this.input = function (key) { 

    if (key.keyCode == 37) { 
     this.offSetX--; 
     console.log(this.offSetX); 
    } 
    if (key.keyCode == 39) { 
     this.offSetX++; 
     console.log(this.offSetX); 
    } 


}; 


this.start = function (id) { 
    var _this = this; 

    this.init(id); 
    this.interval = setInterval(function() { 
     _this.canvas.width = _this.canvas.width; 
     _this.main(); 
    }, 30); 
} 

}};

+0

'this.input' 메소드의 첫 번째 줄에'console.log (this)'를 추가하십시오. 그런 다음'window.addEventListener ("keyup", game.input);를 작성한 후'console'을 확인한 다음 해당 코드를 내 대답으로 바꾸고 다시 확인하십시오. – Engineer

답변

2

이 시도 : input 방법, "this"는 (모든 "offSetX" 방법이없는) window 개체 수없는 이유를

window.addEventListener("keyup", function(key){ 
    game.input.apply(game,[key]); 
}); 

문제는 window.addEventListener("keyup", game.input) 선으로했다, 당신은 window 개체에 대한 핸들러를 추가, 그건 game 개체