Javascript事件侦听器

英镑

我正在尝试用Javascript做一个简单的Pong游戏。我有一个Pong类,我想创建一种根据鼠标的移动方式来移动播放器矩形的方法:

class Player 
{
  constructor()
  {
   // do stuff
  }
}

class Pong
{
  constructor(canvas)
  {
   //do stuff
   this.player1 = new Player(true); // Create an instance of another class

  }

  handleMouseMove(event)
  {
    var y = event.clientY;

    // this.player1 is undefined!!
    console.log("this.player1: "+this.player1);
    this.player1.pos.y = y;
  }


function main()
{
  // Initialize canvas and context
  canvas = document.getElementById('mycanvas');

  const pong = new Pong(canvas);
  canvas.addEventListener('mousemove', pong.handleMouseMove);
}

每当我开始移动鼠标时,它就会告诉我player1是未定义的。如何将类方法设置为事件侦听器,并使它知道类的成员?

易卜拉欣·马尔里尔

这是因为this在事件侦听器内部引用了触发事件的元素(画布)。您可以this使用bind这样绑定关键字

canvas.addEventListener('mousemove', pong.handleMouseMove.bind(pong));
//                                                       ^^^^^^^^^^^

bind将返回一个函数,该函数的this关键字设置为您给它提供的任何参数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章