2013-02-25 40 views
1

我想用Jvascript製作遊戲引擎。到目前爲止,我有:從對象內部調用setInterval 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(); 

但畫布沒有顯示;爲什麼?

回答

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(); 
} 
+0

感謝您的鏈接,這已經幫助了很多:)將盡我所能接受! – Griff 2013-02-25 04:16:40

+1

你的'或者使用閉包:'部分是錯的 – Musa 2013-02-25 04:19:51

+0

我不能接受我有3分鐘;) – Griff 2013-02-25 04:20:53

1

你永遠不會打電話setInterval

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

您需要在初始化後,打電話給你的gameEnginerun()功能。您可能還想將您的gameEngine存儲在一個變量中。

例子:

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

或者,如果你不希望有打電話來說,你的對象定義的堅持到底this.run()。這消除了存儲對你的gameEngine對象的引用的需要,儘管你可能仍然應該爲以後參考。

+0

我不建議讓構造函數除初始化值之外做任何其他工作(第2段)。 JSLint甚至會抱怨 – 2013-02-25 04:22:47