Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法在Javascript对象上引用方法_Javascript - Fatal编程技术网

无法在Javascript对象上引用方法

无法在Javascript对象上引用方法,javascript,Javascript,我正在用Javascript编写Pong的一个版本。我有一个游戏对象,我使用prototype属性来定义它的方法。我得到以下错误:“未定义不是函数”。它被抛出到Game.prototype.step函数中,因此这里没有定义this.update。以下是游戏对象的代码: (function(root) { var Pong = root.Pong = (root.Pong || {}); var Game = Pong.Game = function() { this.canva

我正在用Javascript编写Pong的一个版本。我有一个游戏对象,我使用prototype属性来定义它的方法。我得到以下错误:“未定义不是函数”。它被抛出到Game.prototype.step函数中,因此这里没有定义this.update。以下是游戏对象的代码:

(function(root) {
  var Pong = root.Pong = (root.Pong || {});

  var Game = Pong.Game = function() {
    this.canvas = document.getElementById('canvas');
    this.canvas.width = 800;
    this.canvas.height = 400;
    this.context = canvas.getContext('2d');
    this.maxStartSpeed = 10;
    this.keysDown = {};
    this.player2 = new Pong.Player({'player': 2});
    this.player1 = new Pong.Player({'player': 1});
    this.ball = new Pong.Ball(400, 200);
  }

  Game.prototype.update = function() {
    this.player1.update();
    this.player2.update();
    this.ball.update(player1.paddle, player2.paddle);
  };

  Game.prototype.render = function() {
    this.context.fillStyle = "#bdc3c7";
    this.context.fillRect(0, 0, width, height);
    this.player1.render();
    this.player2.render();
    this.ball.render();
  };


  Game.prototype.animate =  function(callback) { 
    window.setTimeout(callback, 1000/60) 
  };

  Game.prototype.step = function() {
    this.update();
    this.animate(this.step);
  };

  window.addEventListener("keydown", function (event) {
    Game.keysDown[event.keyCode] = true;
  });

  window.addEventListener("keyup", function (event) {
    delete Game.keysDown[event.keyCode];
  });

  window.onload = function() {
    document.getElementById('canvas-container').appendChild(canvas);
    game = new Game();
    game.animate(game.step);
  };  

})(this);

setTimeout将更改作用域。要保持适当的范围,您需要使用

改变

this.animate(this.step);

您需要对其他动画调用执行相同的操作

window.setTimeout(回调,1000/60)
回调的上下文更改为
窗口
<代码>窗口。未定义更新
。可能重复
this.animate(this.step.bind(this));