我是 JavaScript 新手。因此,这个问题有点令人困惑。我试图简单地定义一个计数器并在类方法中递增它,但它的行为不像我期望的那样。专门console.log(this.tick_count);
打印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 背景,我觉得这种行为很奇怪。我应该如何正确设置我的类变量?