RobotEyes
RobotEyes

Reputation: 5250

Javascript 'object has no method' error

This seems to be a popular question on this site but previous answers haven't solved this instance of the problem.

I have the beginnings of a game engine on a node.js server but when I set it going I get the following error occuring in the loop method: Object #<Timer> has no method update.

I thought I was setting the prototype to have an update method with GameEngine.prototype.update = function(){ ... };

Any help in solving this problem would be much appreciated. Thank you.

Here's the entire code:

function GameEngine(){
    this.fps = 1000/60;
    this.deltaTime = 0;
    this.lastUpdateTime = 0;
    this.entities = [];
}

GameEngine.prototype.update = function(){
    for(var x in this.entities){
        this.entities[x].update();
    }
}

GameEngine.prototype.loop = function(){
    var now = Date.now();
    this.deltaTime = now - this.lastUpdateTime;
    this.update();
    this.lastUpdateTime = now;
}

GameEngine.prototype.start = function(){
    setInterval(this.loop, this.fps);
}

GameEngine.prototype.addEntity = function(entity){
    this.entities.push(entity);
}

var game = new GameEngine();
game.start();

Upvotes: 2

Views: 1437

Answers (1)

Bergi
Bergi

Reputation: 665456

This seems to be a popular question on this site

Yes.

but previous answers haven't solved this instance of the problem.

really? Which ones have you found?


The context of the "method" (this) is lost when the function is executed by a timeout/event listener/etc.

GameEngine.prototype.start = function(){
    var that = this;
    setInterval(function(){
       that.loop();
    }, this.fps);
}

or

GameEngine.prototype.start = function(){
    setInterval(this.loop.bind(this), this.fps);
}

Upvotes: 7

Related Questions