简体   繁体   English

如何从匿名函数访问对象实例

[英]How to access object instance from anonymous function

I am dealing with the following situation. 我正在处理以下情况。

I have to use a method from the class, but I have to call a callback too... Look at the code, I have created the _this var because I don't know how to access the DeviceAnalyzer instance from inside the anonymous function... 我必须使用该类中的方法,但我也必须调用回调...看代码,我创建了_this var,因为我不知道如何从匿名函数内部访问DeviceAnalyzer实例。 ..

Is there another way? 还有另一种方法吗? I think the way I did it is kind of nasty haha 我觉得我的做法有点讨厌

DeviceAnalyzer.prototype.pingProcess = function(deviceInfo, callback) {
    var _this = this;
    netutils.ping(host.ipAddress, function(isAlive) {
        deviceInfo.isAlive = isAlive
        _this.emit('device', deviceInfo);
        callback(null, deviceInfo);
    });
};

With ES6 and anonymous function you do not have to set this or bind it. 使用ES6和匿名功能,您不必设置或绑定它。

DeviceAnalyzer.prototype.pingProcess = function(deviceInfo, callback)    {
  netutils.ping(host.ipAddress, (isAlive) => {
      deviceInfo.isAlive = isAlive
      this.emit('device', deviceInfo);
      callback(null, deviceInfo);
  });
};

With IIFE IIFE

DeviceAnalyzer.prototype.pingProcess = function(deviceInfo, callback) {
    (function (that) {
      return netutils.ping(host.ipAddress, function(isAlive) {
        deviceInfo.isAlive = isAlive
        that.emit('device', deviceInfo);
        callback(null, deviceInfo);
    }))(this);
};

The above approach is fine. 上面的方法很好。

An alternative would be to use bind 一种替代方法是使用bind

DeviceAnalyzer.prototype.pingProcess = function(deviceInfo, callback) {
    netutils.ping(host.ipAddress, function(isAlive) {
        deviceInfo.isAlive = isAlive
        this.emit('device', deviceInfo);
        callback(null, deviceInfo);
    }.bind(this));
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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