需要帮助理解clousures和prototypes,我在函数内调用循环方法,问题是,当我调用"循环"返回"不是函数"这是一个例子:
window.onload= startGame();
var theGame;
function startGame(){
theGame = new game();
theGame.loop(); /*im calling the method*/
}
function game(){
this.canvas=document.getElementById("breakout");
this.context = this.canvas.getContext('2d');
this.canvas.width=window.innerWidth;
this.canvas.height=window.innerHeight;
// this.loop(); /*¿can i call it here too?*/
this.speed = 100;
}
game.prototype.loop = function() {
console.log( this.speed+=1);
var self = this;
requestAnimationFrame(function(){
self.loop();
});
};
当我打电话给" LOOP"方法浏览器错误 "未捕获的TypeError:theGame.loop不是函数"
答案 0 :(得分:2)
问题是你错误地设置了onload事件处理程序,因为你正在调用该函数而不是简单地引用它。
window.onload= startGame();
应该是:
window.onload = startGame;