为什么这个Javascript Prototype代码失败了?

时间:2013-08-04 00:39:22

标签: javascript prototype typeerror

我对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'

有关如何解决此问题的想法吗?

2 个答案:

答案 0 :(得分:2)

这是因为你正在使用setInterval(),所以你的tick函数没有得到你期望的'this'。你需要这样做:

Game.prototype.Init = function() {
    var that = this;
    fps=60
    this.loadGame("cvs");
    setInterval(function() { that.tick.call(that); }, 1);
}

Google为“javascript this”或“javascript call”或“javascript apply”获取更多信息。

答案 1 :(得分:1)

在JavaScript中,this的值是动态的,取决于函数的调用方式。由于您正在使用画布,我们可以假设bind可用,因此这应该有效:

setInterval(this.tick.bind(this), (1/fps)*1000);

注意:您可能还希望使用requestAnimationFrame来获得更好的帧速率。

相关问题