Javascript: creating a constant function

I understand that such a question is asked quite often (I probably read each of them in the last few days, trying to figure out how to fix it), but in this case, although I’m sure that I know why this is happening, I’m struggling trying to implement the actual solution.

I am creating a small application using Node.js but having problems creating an object with prototype functions that will not lose their binding when passing them.

Here is what I still have:

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 the aFoo.sendData function to use as a callback causes it to lose its binding to aFoo, so it cannot find the send function in Foo.

How do I change Foo so sendData supports binding to Foo? Is there a better way to structure this code so that it is not necessary?

+1
source share
1 answer

You simply transfer the anFoo.sendData call to an anonymous function:

 aBar.getSomething(data, function () { aFoo.sendData(); }); 

Since your link is aFoo.sendData , the link to this inside sendData no longer aFoo . When using an anonymous function, you do not reference this function; you just call it as an aFoo instance aFoo , so this is still aFoo .

+1
source

Source: https://habr.com/ru/post/1269738/


All Articles