[removed] Creating a persistently bound function

2020-04-30 03:03发布

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?

1条回答
Bombasti
2楼-- · 2020-04-30 03:08

You simple wrap the call to aFoo.sendData in an anonymous function:

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

Because your referencing aFoo.sendData, the reference to this inside sendData is no longer aFoo. When using the anonymous function, you're not referencing the function; you're simply invoking it as a method on the aFoo instance, so this is still aFoo.

查看更多
登录 后发表回答