Link to "this" from javascript callback

Something always bothered me about how I do object oriented coding in Javascript. When there is a callback, I often want to refer to an object that was originally called a function, which forces 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, creating an extra variable has always seemed ... excessive for me. Also, I have to wonder if this can cause problems (circular links? Un-GCd objects?) By passing the variable "me" back to the callback.

Is there a better way to do this? Is this approach evil?

+6
source share
5 answers

This is what Function.bind() for:

 MyClass.prototype.doSomething = function(obj, callback) { obj.loadSomething((function(err, result) { this.data = result; callback(null, this); }).bind(this)); } 
+8
source

AFAIK, what you do is an accepted template for this kind of thing and does not cause any problems. Many people use either "I" or "that", because the stored link - "I" can be more intuitive if you come from the background in python.

+7
source

This is normal behavior for JavaScript. The context for this has changed for the loadSomething object, and the reason for having a callback is to capture closure references, such as your me variable.

+3
source

You can associate this with an inner function area

 MyClass.prototype.doSomething = function(obj, callback) { obj.loadSomething(function(err, result) { this.data = result; callback(null, this); }.bind( this )); } 
+3
source

This is the most common way I've come across this; I usually use var self = this ;, but its just a name. Despite the fact that this is an additional variable, given the overhead of javascript and the fact that it does not duplicate the object, this does not really affect performance.

+1
source

All Articles