I’m trying to run the following code, but get an error in the gameLoop function saying: JavaScript runtime error: Object doesn’t support property or method ‘update’.
I’m a beginning JavaScript programmer. Can you spot what is wrong with this code?
function Core(context) {
this.context = context;
this.fps = 500;
this.sprite = new Sprite();
}
Core.prototype.run = function() {
setInterval(this.gameLoop, this.fps); // <<<< PROBLEM
}
Core.prototype.gameLoop = function () {
this.update();
this.draw();
}
Core.prototype.update = function () {
this.sprite.x += 50;
this.sprite.y += 50;
}
Core.prototype.draw = function () {
this.context.clearRect(0, 0, 300, 300);
this.context.fillRect(this.sprite.x, this.sprite.y, 50, 50);
this.context.fillText('x: ' + this.sprite.x + ' y: ' + this.sprite.y, 10, 250);
}
In JavaScript,
thisis defined entirely by how a function is called, not where or how it’s defined. The problem is thatsetIntervaldoesn’t call your code with the correctthisvalue. To fix:On JavaScript engines that have ES5 features (or if you’re using an ES5 “shim”), you can change
Coreto:More reading:
thisSide note: Your code relies on the horror that is Automatic Semicolon Insertion. (All of your function assignments —
Core.prototype.run = function() { ... }) need semicolons after the closing}.)