无法读取未定义的 属性 `xxx`

Cannot read property `xxx` of undefined

我正在使用 NodeJS 尝试制作一个基本的 Socket.IO 服务器来享受它的乐趣,但我 运行 遇到了一个让我困惑不已的问题。

这是我的服务器代码。很短,只有一个事件。

// Create the server and start listening for connections.
var s_ = require('socket.io')(5055);
var Session = require('./Session');

var connections = [];

var dummyID = 0;

// Whenever a connection is received.
s_.on('connection', function(channel) {
    connections[channel] = new Session(channel, ++dummyID);;
    console.log("Client connected with the ID of " + dummyID);

    // Register the disconnect event to the server. 
    channel.on('disconnect', function() {
        delete connections[channel];
        console.log("A Client has disconnected.");
    });

    channel.on('login', function(data) {
        if(data.username !== undefined && data.password !== undefined) {
            var session = connections[channel];
            if(session !== undefined) {
                session.prototype.authenticate(data.username, data.password);
            }
        }
    });

});

这一行抛出错误:

session.prototype.authenticate(data.username, data.password);

说"authenticate"不能在undefined上调用,也就是说session的原型是undefined。根据上面的检查,会话本身不是未定义的。这里是Session.js

var Session = function(channel, dummyID) {
    this.channel = channel;
    this.dummyID = dummyID;
};

Session.prototype = {
    authenticate: function(username, password) {
        if(username == "admin" && password == "admin") {
            this.channel.emit('login', {valid: true});
        } else {
            this.channel.emit('login', {valid: false});
        }
    }
};

module.exports = Session;

如您所见,原型清晰可见,我正在导出 Session 对象,我真的很困惑问题出在哪里。任何帮助将不胜感激。

只需调用您添加到对象原型的函数

session.authenticate(data.username, data.password);

This article 非常清楚地解释了原型继承链,尤其是用图。

我自己的另一个提示:javascript 中的所有对象在继承链中都有一个 __proto__ 属性,记住这一点会有很大帮助。