从对象Javascript中调用setInterval?

时间:2013-02-25 04:07:43

标签: javascript object canvas game-engine

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

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();

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

4 个答案:

答案 0 :(得分:5)

this is becoming detached when passing this.loop to setInterval.常见解决方案:

Function.bind:

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

use a closure:

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

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

new gameEngine().run();

// or 

function gameEngine() {

    // snip...

    this.run();
}

答案 1 :(得分:1)

您永远不会致电setInterval

var ngin = new gameEngine();
ngin.run();

答案 2 :(得分:1)

初始化后,您需要在run()上调用gameEngine功能。您可能还想将gameEngine存储在变量中。

示例:

var myGameEngine = new gameEngine();
myGameEngine.run();

或者,如果您不想调用run,请在对象定义的末尾粘贴this.run()。这样就不需要存储对gameEngine对象的引用,尽管您可能仍需要以后参考。

答案 3 :(得分:1)

const ngin = new gameEngine()
ngin.run()