0

I foolishly thought that a good way to get into javascript and making games would be to make a game in javascript. I used this as a tutorial, but I'm an OOP programmer, so I thought I would make it OOP. In brief my new version is this:

function Game(){this.whatever = that;...};
Game.prototype.reset = function() {...};
Game.prototype.update = function(dt) {...};
Game.prototype.render = function() {...};
Game.prototype.main = function() {
    var now = Date.now();
    var delta = now-this.then;
    this.update(delta/1000);
    this.render();
    this.then = now;

    requestAnimationFrame(this.main);
};

var g = new Game();
g.reset();
g.main();

I can't figure out what's wrong, but I get this error: TypeError: this.update is not a function

I added the console.log for this and it shows me that it runs main twice on the correct object, and then suddenly on the third time this is the window. What am I doing wrong?

Hovestar
  • 1,544
  • 4
  • 18
  • 26
  • `requestAnimationFrame(this.main.bind(this));` - read up on [how `this` works in JS](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this). – nnnnnn Jul 06 '16 at 01:10
  • @nnnnnn That was it. Can you put it as an answer so I can accept it? – Hovestar Jul 06 '16 at 01:19
  • I put a quick comment rather than posting an answer because I knew this was a duplicate (of quite a few other questions, but Phil found one before I did). – nnnnnn Jul 06 '16 at 01:53

0 Answers0