如何在JS中保存'this'变量?

时间:2018-08-31 16:17:29

标签: javascript oop closures 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 " + self.imei);


  };
}

我正在创建设备类的新对象,并希望将每个对象的'this'值保存到自变量中,这样我就可以在回调中使用它而没有任何麻烦。但是正在发生的事情是,当创建两个对象a和b时,对象a的self值也更改为b的值,从而产生了模糊的结果。有人可以解释为什么吗? 连接到服务器的新设备会更改每个先前对象的自身值。

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

1 个答案:

答案 0 :(得分:1)

问题是只有一个Device.prototype.saveLocation函数。每次创建新设备时,都会用最新的设备覆盖该功能,其中的最后一个值为self

原型函数不应在构造函数中创建,而应仅定义一次。它不需要使用self,因为它接收到的对象是this

您只需要在构造函数中定义的回调函数中使用self,而无需在对象或原型的方法中使用

所以应该是这样。

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

您还可以使用箭头函数定义回调函数,然后从定义的地方继承this

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