I'm new to JavaScript. Hence this problem is a bit confusing. I'm trying to simply define a counter and increment it in a class method but its not behaving as I expect it to. Specifically console.log(this.tick_count);
prints 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>
Coming from a Python background I find this behavior strange. How should I set up my class variables correctly?