我是JavaScript新手。因此這個問題有點混亂。我試圖簡單地定義一個計數器並在類方法中增加它,但它不像我預期的那樣運行。具體console.log(this.tick_count);
打印undefined
。JavaScript中的類變量返回undefined
的JavaScript:
function Game() {
this.fps = 50;
this.ticks = 3;
this.current_time = (new Date).getTime();
this.draw_object = document.getElementById('game_canvas').getContext('2d');
this.tick_count = 0;
}
Game.prototype.update = function (time) {
this.current_time = time;
}
Game.prototype.draw = function() {
this.draw_object.fillRect(10, 10, 55, 50);
}
Game.prototype.run = function() {
self.setInterval(this.tick, 1000/(this.fps * this.tick));
}
Game.prototype.tick = function() {
this.tick_count++;
console.log(this.tick_count);
}
function start_game() {
var game_object = new Game();
game_object.run();
}
HTML:
<body onload="start_game()">
<canvas id="game_canvas" width="1024" height="1024"></canvas>
</body>
從Python的背景,我覺得這種行爲奇怪的到來。我應該如何正確設置我的類變量?
你在哪裏定義'self'?而'setInterval'內的'this'並不是你想象的那樣。 – Mathletics
[Javascript setInterval範圍問題]的可能的重複(http://stackoverflow.com/questions/11333311/javascript-setinterval-scoping-issue) – Mathletics
嘗試'self.setInterval(this.tick.bind(this),1000 /( this.fps * this.tick));'看看它是怎麼回事 – PSL