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?