我试图在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未定义。如何将类方法设置为事件监听器并让它知道类'成员?
答案 0 :(得分:3)
因为事件监听器中的this
引用了触发事件的元素(画布)。您可以使用bind绑定this
关键字,如下所示:
canvas.addEventListener('mousemove', pong.handleMouseMove.bind(pong));
// ^^^^^^^^^^^
bind
会返回一个函数,其this
关键字设置为您为参数设置的任何内容。
答案 1 :(得分:1)
在我看来,这是javascript中最糟糕的部分之一。当您将pong.handleMouseMove
传递给addEventListener
时,您正在传递函数本身。在该上下文中,当事件触发时,它在Pong
实例的上下文之外调用该函数。您需要在handleMouseMove
上致电bind,如下所示:
canvas.addEventListener('mousemove', pong.handleMouseMove.bind(pong));
bind
,并返回一个可以传递的新函数,并确保函数内的this
绑定到指定的参数(在本例中为pong
})。
编辑:ibrahim mahrir的另一个答案是错误的,您必须将pong
实例传递给bind
函数。无论你传递的是this
将被绑定到你绑定的函数内部。