我在我的一个函数中使用 socket.io 侦听器来侦听“失败者”事件,以告诉客户端另一个客户端赢了。但是,我不能在 socket.on 函数中使用“this”关键字来谈论我的客户端,因为 this 指的是套接字本身。我会以错误的方式解决这个问题吗?或者可以通过其他方式访问客户端对象,比如超级?
socket.on('loser', function() {
//Remove all current objects then restart the game.
//THIS PART DOESN'T WORK, SINCE 'THIS' NO LONGER REFERS TO
//THE GAME OBJECT, BUT INSTEAD REFERENCES THE SOCKET LISTENER.
for(var i = 0; i < this.board.objects.length; i++)
{
this.board.remove(this.board.objects[i]);
}
//WORKS AS EXPECTED FROM HERE ON...
Game.setBoard(1, new TitleScreen(gameType,
"Loser!",
"Press Space to Play Again",
playGame));
});