为什么这个Javascript原型代码失败了

Why does this Javascript Prototype code fail?

本文关键字:代码 失败 原型 Javascript 为什么      更新时间:2023-09-26

我对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来获得更好的帧速率。