从对象Javascript中调用setInterval?

Gri*_*iff 1 javascript canvas object game-engine

我正在尝试使用Jvascript制作游戏引擎.到目前为止,我有:

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();
Run Code Online (Sandbox Code Playgroud)

但画布没有出现; 为什么?

Mat*_*all 5

thisthis.loop去往时变得分离setInterval.常见解决方案

Function.bind:

this.run = function() {
    setInterval(this.loop.bind(this), this.framerate);
};
Run Code Online (Sandbox Code Playgroud)

或者使用一个闭包:

var self = this;
this.run = function() {
    setInterval(function () {
        self.loop();
    }, this.framerate);
};
Run Code Online (Sandbox Code Playgroud)

然后,你需要实际调用run方法:

new gameEngine().run();

// or 

function gameEngine() {

    // snip...

    this.run();
}
Run Code Online (Sandbox Code Playgroud)