Abhishek Yadav
Abhishek Yadav

Reputation: 362

How to save the 'this' variable in JS?

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

Upvotes: 0

Views: 63

Answers (1)

Barmar
Barmar

Reputation: 782564

The problem is that there's only one Device.prototype.saveLocation function. Every time you create a new device, you're overwriting this function with the most recent one, which has the last value of self in it.

Prototype functions should not be created in the constructor, they should be defined just once. It doesn't need to use self, because it receives the object it's called on as this.

You only need to use self in callback functions that are defined in the constructor, not methods of the object or prototype.

So it should be like this.

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 " + this.imei);
};

You can also define the callback function using an arrow function, then it inherits this from where it was defined.

function Device(socket) {

  this.imei = false;
  this.status = false; //maintaining the logged in status
  let self = this; //saving this variable

  this.on('data', () => { //Event on the device object

    //You can access this.imei here

  });
}

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 " + this.imei);
};

Upvotes: 1

Related Questions