1

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...

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);
    });
};
4
  • There is nothing wrong with it. I usually do something similar, like "var self = this;" Commented Jan 14, 2016 at 14:16
  • code looks good. No need of over complicating the code just to access this. This code is legible and yields the result same as other solutions. Commented Jan 14, 2016 at 14:23
  • You have three other options : apply,call or bind just pick one. Commented Jan 14, 2016 at 14:27
  • The answer from magnudae seams to be cleaner! Commented Jan 14, 2016 at 14:32

3 Answers 3

2

With ES6 and anonymous function you do not have to set this or bind it.

DeviceAnalyzer.prototype.pingProcess = function(deviceInfo, callback)    {
  netutils.ping(host.ipAddress, (isAlive) => {
      deviceInfo.isAlive = isAlive
      this.emit('device', deviceInfo);
      callback(null, deviceInfo);
  });
};
Sign up to request clarification or add additional context in comments.

2 Comments

I think this is the best solution
Remember that you can not run ES6 directly in every browser. This means you have to transpile it to ES5, but ES6 contains so much niceness its worth it =)
1

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

Comments

0

The above approach is fine.

An alternative would be to use 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));
};

2 Comments

Don't you think you are overriding the this. What if netutils.ping is sending some objects/function by binding to this to the callback like consider this.event sent on click events callbacks in jquery.
@Nirus, absolutely, in that case, this would not be the optimal solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.