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 not a variable.this
cannot be closed over. The approach is fine.new Function("..")
to "avoid issues".)this
to a meaningful name instead of having the same "variable" refer to a bunch of different objects over the course of a single logical function. (Where, given the nature of JS code, a "logical function" can contain quite a few other tiny ones, likejQuery.each()
callbacks, event handlers, or continuations.)