使用Javascript:创建一个持久绑定功能 [英] Javascript: Creating a persistently bound function

查看:118
本文介绍了使用Javascript:创建一个持久绑定功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这样一个问题是问pretty频繁(我大概看过过去几天试图了解如何解决这个问题他们每个人) - 但在这种情况下,当我相当有信心,我知道为什么发生这种情况,我挣扎实现一个实际的解决方案。

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.

我建立使用Node.js的,但有与创建与原型功能不会丧失时,他们正在通过周围的绑定的对象麻烦的小应用程序。

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);

正如你可能想象,传递一个用作回调函数aFoo.sendData导致它失去其绑定到aFoo,所以无法找到富发送功能。

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.

我将如何修改美孚这样的SendData保持其绑定到富?有没有更好的方法来组织这个code,使这是没有必要的?

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?

推荐答案

您简单封装在一个匿名函数调用aFoo.sendData:

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

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

由于您参考 aFoo.sendData ,提到这个的SendData 不再<$​​ C $ C> aFoo 。当使用匿名函数,你不引用功能;你只是调用它作为对 aFoo 实例的方法,那么这个还是 aFoo

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.

这篇关于使用Javascript:创建一个持久绑定功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆