function Device(socket) {
this.imei = false;
this.status = false; //maintaining the logged in status
let self = this; //saving this variable
this.on('data', function() { //Event on the device object
//I want to access self.imei
});
Device.prototype.saveLocation = function(parts) {
//Here the value of self changes to the value of self of the recent object created
console.log("In save location : IMEI " + self.imei);
};
}
I am creating new objects of the device class and wanted to save the 'this' value of every object to self variable so that I can use that in callbacks without any hassle. But what is happening is that when two objects a and b are created, the value of self of object a also changes to that of b which produces ambigous results. Can someone explain why? New devices that connect to the server, changes the self value of every previous object.
const server = net.createServer(function (socket) {
socket.name = socket.remoteAddress + ":" + socket.remotePort;
socket.device = new Device(socket);
clients.push(socket);
let bufferString = 'cddwcdc';
socket.emit('data',bufferString);
});