Javascript: Creating a persistently bound function

可紊 提交于 2019-12-02 09:34:47

问题


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:


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.



来源:https://stackoverflow.com/questions/4967689/javascript-creating-a-persistently-bound-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!