为什么这个Javascript原型代码失败了
Why does this Javascript Prototype code fail?
我对javascript有点陌生,在编写游戏时遇到了这个错误。这让我很困惑,因为这个函数看起来和其他所有函数一样,但它不起作用。
function Game() {}
Game.prototype.loadGame = function(x) {
this.cvs=document.getElementById(x);
this.cvs.height=480;
this.cvs.width=640;
this.sprites=[];
this.ctx=cvs.getContext("2d");
};
Game.prototype.update = function() {
console.log("u");
};
Game.prototype.draw = function() {
this.drawCircle(320, 240, 10, "green")
};
Game.prototype.drawCircle = function(centerX, centerY, radius, color) {
this.ctx.beginPath();
this.ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
this.ctx.fillStyle = color;
this.ctx.fill();
};
Game.prototype.tick = function() {
this.update();
this.draw();
};
Game.prototype.Init = function() {
fps=60
this.loadGame("cvs");
setInterval(this.tick, (1/fps)*1000);
};
g = new Game();
g.Init();
我得到错误:Uncaught TypeError: Object [object global] has no method 'update'
你知道怎么解决这个问题吗?
这是因为您使用的是setInterval(),所以您的tick函数没有得到您期望的"this"。你需要这样做:
Game.prototype.Init = function() {
var that = this;
fps=60
this.loadGame("cvs");
setInterval(function() { that.tick.call(that); }, 1);
}
谷歌搜索"javascript this"、"javascript call"或"javascript application"以获取更多信息。
在JavaScript中,this
的值是动态的,取决于函数的调用方式。由于您使用的是画布,我们可以假设bind
是可用的,所以这应该是有效的:
setInterval(this.tick.bind(this), (1/fps)*1000);
注意:您可能还想使用requestAnimationFrame
来获得更好的帧速率。
相关文章:
- 如何使用onclick事件触发此代码.我尝试过,但失败了
- 解析云代码不会记录/警告成功或失败
- jQuery代码在Firefox中工作,但在IE中失败
- 执行Haxe代码时Ant构建失败
- *简单*解析云代码查询失败”;TypeError:无法调用方法'获取'未定义的“检索该信息”;
- 云代码(javascript)失败,原因是:{代码:1,消息:内部错误
- 只有从Node运行时,Rsync才会失败,退出代码为23
- 弹出窗口代码失败
- 为什么我的窗口导航代码失败
- JavaScript 迷宫代码失败
- 跨域请求的 Ajax 代码失败
- firefox中的Cookie代码失败
- 没有语法错误,但代码失败
- 重新生成代码失败
- 为什么这个Javascript原型代码失败了
- Javascript代码失败
- Javascript中的HTML代码失败
- Express.js 4-路由器分区示例代码失败
- EventListener长代码失败,原因
- 上传最后一个文件片时代码失败.(javascript, HTML 5)