Javascript事件侦听器
我正在尝试用Javascript制作一个简单的乒乓球游戏。我有一个Pong类,我想创建一个基于鼠标移动方式移动播放器矩形的方法:Javascript事件侦听器,javascript,addeventlistener,Javascript,Addeventlistener,我正在尝试用Javascript制作一个简单的乒乓球游戏。我有一个Pong类,我想创建一个基于鼠标移动方式移动播放器矩形的方法: class Player { constructor() { // do stuff } } class Pong { constructor(canvas) { //do stuff this.player1 = new Player(true); // Create an instance of another class
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
关键字:
canvas.addEventListener('mousemove', pong.handleMouseMove.bind(pong));
// ^^^^^^^^^^^
bind
将返回一个函数,其this
关键字设置为您作为参数赋予它的任何值。这是因为事件侦听器中的this
引用了触发事件的元素(画布)。您可以使用如下方式绑定this
关键字:
canvas.addEventListener('mousemove', pong.handleMouseMove.bind(pong));
// ^^^^^^^^^^^
bind
将返回一个函数,其this
关键字设置为您作为参数指定的任何值。我认为这是javascript最糟糕的部分之一。当您将pong.handleMouseMove
传递到addEventListener
时,您传递的是函数本身。在该上下文中,当事件激发时,它正在调用Pong
实例上下文之外的函数。您需要调用handleMouseMove
,如下所示:
canvas.addEventListener('mousemove',pong.handleMouseMove.bind(pong));
bind
存在于所有函数中,并返回一个新函数,您可以传递该函数,并确保函数中的此
绑定到指定参数(在本例中,pong
)
编辑:ibrahim mahrir的另一个答案是错误的,您必须将
pong
实例传递给bind
函数。无论你传递什么,都是这个将被分配到你绑定的函数中。在我看来,这是javascript最糟糕的部分之一。当您将pong.handleMouseMove传递到addEventListener
时,您传递的是函数本身。在该上下文中,当事件激发时,它正在调用Pong
实例上下文之外的函数。您需要调用handleMouseMove
,如下所示:
canvas.addEventListener('mousemove',pong.handleMouseMove.bind(pong));
bind
存在于所有函数中,并返回一个新函数,您可以传递该函数,并确保函数中的此
绑定到指定参数(在本例中,pong
)
编辑:ibrahim mahrir的另一个答案是错误的,您必须将
pong
实例传递给bind
函数。无论您传递的是什么,此将被分配到您绑定的函数中。您的Player
类在哪里?Player类在Pong类之外,但在同一文件中。我将编辑我的问题以显示这一点。你的Player
类在哪里?Player类在Pong类之外,但在同一个文件中。我将编辑我的问题来说明这一点。这不是这个
,而是乒乓球
@ChemicalRocketeer是的,我刚刚注意到了!我以为main
在班里Pong
!这不是这个
,而是乒乓
@化学火箭手是的,我刚刚注意到了!我以为main
在班里Pong
!你也可以canvas.addEventListener('mousemove',function(e){pong.handleMouseMove(e);})
-不太好,但我看到了非常普遍的情况……我很感谢你的解释。我接受了另一个答案,因为它更接近顶部(并且在我看到它时已经固定)。谢谢你也可以canvas.addEventListener('mousemove',function(e){pong.handleMouseMove(e);})
-不太好,但我看到了非常普遍的情况……我很感谢你的解释。我接受了另一个答案,因为它更接近顶部(并且在我看到它时已经固定)。谢谢