I find myself assigning \"this\" to a variable so I can easily use it in callbacks and closures.
Is this bad practice? Is there a better way of referring back to the
You could create a proxy for the callback with:
var createProxy = function(fn, scope) {
return function () {
return fn.apply(scope, arguments);
};
};
Using this, you could do the following:
db.User.findById('ABCD', createProxy(function(err, user)) {
this.foo(user);
}, this));
jQuery does something similar with: $.proxy
And, as others have noted using bind
, have a look here if compatibility is an issue:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind#Compatibility