1

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

关于如何解决这个问题的任何想法?

4

2 回答 2

2

这是因为您使用的是 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 apply”以获取更多信息。

于 2013-08-04T00:50:35.823 回答
1

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

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

注意:您可能还想使用requestAnimationFrame更好的帧速率。

于 2013-08-04T01:11:33.977 回答