setInterval不在事件侦听器内重复

时间:2018-06-22 16:52:30

标签: javascript setinterval

我正在尝试使用JavaScript制作蛇游戏,但无法获取setInterval来反复调用函数:

class Game {

  constructor(){
    this.xPosition = 0
    this.yPosition = 0
    this.canvas = document.getElementById("canvas");
    this.ctx = canvas.getContext("2d");
    this.drawSquare(0,0);
  }

  drawSquare(x,y){
    this.xPosition += x
    this.yPosition += y;
    if (this.xPosition < 0){
      this.xPosition = 600;
    }
    else if (this.xPosition > 600){
      this.xPosition = 0;
    }
    if (this.yPosition < 0){
      this.yPosition = 600;
    }
    else if (this.yPosition > 600){
      this.yPosition = 0;
    }
    this.ctx.fillStyle = "#FF0000";
    this.ctx.clearRect(0, 0, 600, 600);
    this.ctx.fillRect(this.xPosition,this.yPosition,60,60);
  }
  moveUp(){
    this.drawSquare(0,-60);
  }
}

var game = new Game();

//add EventListener for keyboard
window.addEventListener("keydown", e => {
  switch (e.key){
    case 'w':
      setInterval(game.moveUp,1000);
      break;
  }
});

当我运行“ setInterval(game.moveUp,1000)”时,遇到TypeError:this.drawSquare不是函数。这让我感到困惑,因为我在顶部明确定义了该函数,并且当我在没有setInterval的情况下在switch外壳中运行game.moveUp()时,错误消失了。

1 个答案:

答案 0 :(得分:4)

问题在于setInterval接受一个函数,而game.moveUp()是一个函数调用 1 ,因此正确的用法是:

setInterval(game.moveUp, 1000);

1 不返回另一个函数。


更新:这解决了在回答了最初的问题之后提出的问题。

您还需要确保this也已绑定。请在下面查看更正后的代码(我已将其下移,因此您可以实际看到它的运动),并进一步研究在JavaScript中绑定此代码。

class Game {

  constructor(){
    this.xPosition = 0
    this.yPosition = 0
    this.canvas = document.getElementById("canvas");
    this.ctx = canvas.getContext("2d");
    this.drawSquare(0,0);
  }

  drawSquare(x,y){
    this.xPosition += x
    this.yPosition += y;
    if (this.xPosition < 0){
      this.xPosition = 600;
    }
    else if (this.xPosition > 600){
      this.xPosition = 0;
    }
    if (this.yPosition < 0){
      this.yPosition = 600;
    }
    else if (this.yPosition > 600){
      this.yPosition = 0;
    }
    this.ctx.fillStyle = "#FF0000";
    this.ctx.clearRect(0, 0, 600, 600);
    this.ctx.fillRect(this.xPosition,this.yPosition,60,60);
  }
  moveUp(){
    console.log('move up');
    this.drawSquare(0, 60);
  }
}

var game = new Game();

//add EventListener for keyboard
window.addEventListener("keydown", e => {
  switch (e.key){
    case 'w':
      setInterval(game.moveUp.bind(game) ,1000);
      break;
  }
});
<canvas id="canvas"> </canvas>