Search code examples
javascriptobjectcanvasgame-engine

setInterval invoked from inside an object Javascript?


I am trying to make a game engine with Jvascript. So far I have:

function gameEngine() {

    this.canvas = $('canvas')[0];
    this.ctx = this.canvas.getContext('2d');
    this.framerate = 20;

    this.resetCanvas = function() {
        this.ctx.fillStyle = 'red';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    };

    this.loop = function() {
        this.resetCanvas();
    };

    this.run = function() {
        setInterval(this.loop, this.framerate);
    };
}

new gameEngine();

But the canvas is not showing up; why?


Solution

  • this is becoming detached when passing this.loop to setInterval. Common solutions:

    Function.bind:

    this.run = function() {
        setInterval(this.loop.bind(this), this.framerate);
    };
    

    Or use a closure:

    var self = this;
    this.run = function() {
        setInterval(function () {
            self.loop();
        }, this.framerate);
    };
    

    Then you need to actually call the run method:

    new gameEngine().run();
    
    // or 
    
    function gameEngine() {
    
        // snip...
    
        this.run();
    }