Reputation: 16182
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.
Upvotes: 1
Views: 1408
Reputation: 55
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.
Upvotes: 0
Reputation: 6373
just call the function you added to the objects prototype
session.authenticate(data.username, data.password);
Upvotes: 2