0

!CLOSED!

Hey i've been messing around with Objects in JavaScript and i've come to a problem:

function Game(name, canvas, width, height, fps)
{
    this.name = name;
    this.canvas = document.getElementById(canvas);
    this.ctx = this.canvas.getContext('2d');
    this.width = width;
    this.height = height;
    this.fps = fps;

}

Game.prototype.gameloop = function()
{
    //Clear Screen
    this.canvas.width = this.canvas.width;

    //Update
    //Update();
    //Draw
    Draw(this.ctx);//this is now pointing at 'Game'
};

Game.prototype.start = function() { 
    this.interval = setInterval(this.gameloop.bind(this),this.fps); 
};

I can't figure out why in this case the 'this' keyword isn't pointing at 'Game'

Any suggestions?

Fullk33
  • 230
  • 2
  • 9
  • How are you calling `gameloop`? Are you using `new`? – Matt Ball Apr 19 '13 at 20:13
  • 3
    The value of `this` depends on how you *call* a function, not how you define it. We can't see how you call it. – Quentin Apr 19 '13 at 20:14
  • Game.prototype.start = function() { this.interval = setInterval(this.gameloop,this.fps); }; – Fullk33 Apr 19 '13 at 20:14
  • @Fullk33: I added your code to the question. In the future, please edit your question to add more info. Thanks. –  Apr 19 '13 at 20:16
  • 1
    ok thanks i didn't know how to do this ;) – Fullk33 Apr 19 '13 at 20:18
  • If you create an instance of Game--say, var g = new Game(...);, then the context of "this" when you call g.gameloop() should be the object g. – Rick Apr 19 '13 at 20:21
  • @Quintin: Thx alot! It works with the .bind(this) method :D. You never stop learning... – Fullk33 Apr 19 '13 at 20:23
  • @Fullk33: Just keep in mind that `.bind()` isn't available in IE8 and lower. Though you can [patch it in](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind#Compatibility). –  Apr 19 '13 at 20:23

0 Answers0