简体   繁体   中英

Cannot read property `xxx` of undefined

I'm working with NodeJS in an attempt to make a basic Socket.IO server for the fun of it and I've ran into an issue that's confusing me to no ends.

Here's my Server code. Fairly short, only one event.

// 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);
            }
        }
    });

});

The error is thrown on this line:

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

Saying that "authenticate" cannot be called on undefined, meaning the prototype of session is undefined. Session itself is not undefined, as per the check above it. Here is 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;

As you can see the prototype is clearly there, I'm exporting the Session object, and I'm really confused as to what the issue is. Any help would be greatly appreciated.

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

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

This article explains the prototype inheritance chain very clearly, especially with the graph.

And one more tip of myself: everything object in javascript has a __proto__ property in the inheritance chain, keep that in mind helps a lot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM