Something has always bothered me about the way I do object-oriented coding in Javascript. When there's a callback, I frequently want to reference the object which originally called the function, which leads me to do something like this:
MyClass.prototype.doSomething = function(obj, callback) {
var me = this; // ugh
obj.loadSomething(function(err, result) {
me.data = result; // ugh
callback(null, me);
});
}
First off, creating the additional variable alway seemed... excessive to me. Furthermore, I have to wonder if it might end up causing problems (circular references? un-GCd objects?) by passing the "me" variable back to the callback.
Is there a better way to go about this? Is this approach evil?
This is what Function.bind()
is for:
MyClass.prototype.doSomething = function(obj, callback) {
obj.loadSomething((function(err, result) {
this.data = result;
callback(null, this);
}).bind(this));
}
AFAIK, what you are doing is the accepted pattern for this kind of thing, and doesn't cause any issues. A lot of people use either "self" or "that" as the stored reference - "self" can be more intuitive if you come from a python background.
This is normal behavior for JavaScript. The context for this
has changed for the loadSomething
object, and the reason for having the callback is to capture closure references like your me
variable.
You can bind this to the scope of the inner function
MyClass.prototype.doSomething = function(obj, callback) {
obj.loadSomething(function(err, result) {
this.data = result;
callback(null, this);
}.bind( this ));
}
This is the most common way I have seen to handle it, I usually use var self = this;, but its just a name. Even though it is an extra variable, considering the javascript overhead and the fact that it doesn't duplicate the object, it really isn't going to impact performance.