I realise a question like this is asked pretty frequently (I've probably read every one of them over the past few days trying to understand how to fix this) - but in this case, while I'm fairly confident I know why this is happening, I'm struggling to implement an actual solution.
I'm building a small application using Node.js but having trouble with creating an object with prototype functions that won't lose their binding when they're passed around.
Here's what I have so far:
foo.js
var Foo = module.exports = function(server) {
this.server = server;
// some other stuff
};
Foo.prototype.send = function(data) {
server.doStuff(data);
};
Foo.prototype.sendData = function(data) {
// do stuff with data;
this.send(data);
};
bar.js
var Bar = module.exports = function() {
this.dataStore = // data store connection;
};
Bar.prototype.getSomething(data, callback) {
this.dataStore.get(data, function(err, response) {
callback(response);
});
};
main.js
var Foo = require('./foo');
var Bar = require('./bar');
var aFoo = new Foo(server);
var aBar = new Bar();
// at some point do:
aBar.getSomething(data, aFoo.sendData);
As you can probably imagine, passing that aFoo.sendData function for use as a callback causes it to lose its binding to aFoo, so it is unable to find the 'send' function on Foo.
How would I modify Foo so that sendData maintains its binding to Foo? Is there a better way to structure this code so that this isn't necessary?
You simple wrap the call to aFoo.sendData in an anonymous function:
Because your referencing
aFoo.sendData
, the reference tothis
insidesendData
is no longeraFoo
. When using the anonymous function, you're not referencing the function; you're simply invoking it as a method on theaFoo
instance, sothis
is stillaFoo
.