Socket.io - 无法访问'this'对象

时间:2015-08-27 23:11:52

标签: javascript node.js sockets

我正在使用Socket.io在NodeJS中编写游戏。我有一个Player类,其方法为move(),当player.move事件被触发时会被调用。然后,它尝试访问当前对象属性。

这应该可以正常工作,但是当调用move()时,它会产生错误,因为无法访问变量this.location。有没有办法以任何方式访问此变量?谢谢。

这是我的代码:

main.js

var io = require('socket.io')(8080);
var Player = require('./Player');

// All players
var players = {};

io.on('connection', function(socket) {

    // Add a new player
    players[socket.id] = new Player(socket);

    // Remove user from the game
    socket.on('disconnect', function() {
        players[socket.id].__unbind();
    });
});

Player.js

/**
 * Player class
 * @param socket
 * @constructor
 */
function Player(socket) {
    this.socket = socket;
    this.location = {x : 0, y : 0};
    this.__bind();
}

/**
 * Move a player
 * @param {int} x
 * @param {int} y
 */
Player.prototype.move = function(x, y) {
    this.location.x = x;
    this.location.y = y;
};

/**
 * Add event listeners
 * @private
 */
Player.prototype.__bind = function() {
    this.socket.on('player.move', this.move);
};

/**
 * Remove event listeners
 * @private
 */
Player.prototype.__unbind = function() {
    this.socket.removeListener('player.move', this.move);
};

// Exports
module.exports = Player;

生成的错误:

TypeError: Cannot set property 'x' of undefined
    at Socket.Player.move ...(stack trace here)

1 个答案:

答案 0 :(得分:1)

您必须将函数调用绑定到Player对象,以便在调用上下文时不会松开:

=SUM(IIF(Fields!Doc_Type.Value = "Shipments", 1, 0))

您必须绑定要在Player上下文之外执行的所有方法调用。