0

After reviewing a couple of relevant SO questions, I still am not completely clear how I should be handling "this" in callbacks within prototype functions. Here is a self contained example (in node.js), which works fine, but uses the "var self = this" approach, which seems unsatisfying.

var http = require('http');

var myClass = function(){
  this.results = null
  this.options = {
      host: 'stackoverflow.com',
      path: '/questions/11553985/prototype-callback-function-replace-this-value'
  };
};

myClass.prototype.request = function(callback) {
    var self = this; // oof.
    var d;
    req = http.request(this.options, function(response, error) {
        if(error)
            throw(error);
        response.on('data', function (data) {
            d = d + data;
        });
        response.on('end', function() {
            self.results = d; // my real use case does a bit more with 'd'
                              // this is just a trivial example  
            callback();
        });
    });
    req.end();
}

myCallback = function() {
  console.log(inst.results);
}

inst = new myClass;
inst.request(myCallback);

I tried the approach here:

javascript: prototypes with callbacks and 'this'

By adding this directly before the req.end() line above:

req.myinstance = this; // refer to myself in the request object

And then in the response call back:

    response.on('end', function() {
        this.myinstance.results = d;
        callback();
    });

But this.myinstance.results was then undefined.

Is the var self = this acceptable form? What different solutions are there to keeping track of the "parent" object within a function's callback in situations such as this?

Community
  • 1
  • 1
Eric
  • 1,691
  • 16
  • 24
  • quick observation (not sure this addresses the issue though), Your line above req.end() may be misspelled. You are setting req.mysinstance and later referring to this.myinstance in the callback. The first reference has an "s" in between "my" and "instance". – Kevin Sep 24 '14 at 20:44
  • Sorry...that was a typo. Fixed in the question. Does not solve the problem, though. I think the previous question Felix King links to above does addres the issue. Digesting...... – Eric Sep 24 '14 at 21:54

0 Answers0