I am using node.js. I have this handlers.js file:
exports.Handlers = function(prefix) {
this.prefix = prefix;
this.db = new DBInstance();
};
exports.Handlers.prototype.getItemById = function(id) {
var item = this.db.getItemById(id, function(error, item) {
item.name = this.prefix + item.name;
...
...
});
};
When I call:
var h = new Handlers();
h.getItemById(5);
I get an error since the context isn’t the Handlers and this.prefix doesn’t exists. I can fix it using this:
exports.Handlers.prototype.getItemById = function(id) {
var scope = this;
var item = this.db.getItemById(id, function(error, item) {
item.name = scope.prefix + item.name;
...
...
});
};
Is there any better way to pass the context to the callback?
What is the nodejs common way to pass the context to the callback?
Node implements ECMAScript 5, which has
Function.bind().I think that is what you are looking for.
This works, however when using a closure as a callback, like you are doing, the most common way this is done is by storing the context in a variable that can be used in the closure.
This method is more common because many times callbacks can be deep and calling
bindon each callback can be heavy; whereas definingselfonce is easy: