[英]Using this keyword within Socket.io on function
我在其中一個函數中使用socket.io偵聽器,以偵聽“失敗者”事件,以告知客戶端另一個客戶端獲勝。 但是,當在socket.on函數內部時,我不能使用“ 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));
});
函數不包含有關引用它們的對象的任何信息,可以在傳遞函數之前使用.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));
在瀏覽器領域,執行此操作的常用方法是設置一個變量,例如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/zh-CN/docs/JavaScript/Reference/Global_Objects/Function/bind
這樣的事情怎么了?
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]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.