我在我的一个函数中使用了一个socket.io监听器来监听“失败者”事件,告诉客户另一个客户赢了。但是,在socket.on函数内部,我不能使用“this”关键字来讨论我的客户端,因为这指的是套接字本身。我是以错误的方式来做这件事的吗?或者可以通过其他方式访问客户端对象,例如super?
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));
});
答案 0 :(得分:3)
函数不包含有关引用它们的对象的任何信息,您可以使用.bind()
将函数绑定到对象,然后再传递它:
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));
}.bind(this));
答案 1 :(得分:1)
在浏览器版本中,执行此操作的常用方法是在输入函数之前设置var that = this;
之类的变量,然后改用that
。
然而,ECMAScript5引入了bind()
,这可以防止this
的值丢失。当然,在NodeJS中使用它是安全的(不像在浏览器领域,你必须支持旧的浏览器)。
socket.on('loser', (function() {
//Remove all current objects then restart the game.
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));
}).bind(this));
有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
答案 2 :(得分:0)
这样的事情出了什么问题?
var self = this;
socket.on('loser', (function() {
//Remove all current objects then restart the game.
for (var i = 0; i < self.board.objects.length; i++) {
self.board.remove(self.board.objects[i]);
}
}