微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node.js – node js将上下文传递给回调

我正在使用node.js.我有这个handlers.js文件

exports.Handlers = function(prefix) {
    this.prefix = prefix;
    this.db = new DBInstance();
};

exports.Handlers.prototype.getItemById = function(id) {
    var item = this.db.getItemById(id,function(error,item) {
        item.name = this.prefix + item.name;
        ...
        ...
    });
};

我打电话的时候:

var h = new Handlers();
h.getItemById(5);

我得到一个错误,因为上下文不是处理程序,this.prefix不存在.我可以使用这个修复它:

exports.Handlers.prototype.getItemById = function(id) {
    var scope = this;
    var item = this.db.getItemById(id,item) {
        item.name = scope.prefix + item.name;
        ...
        ...
    });
};

有没有更好的方法将上下文传递给回调?
nodejs将上下文传递给回调的常用方法是什么?

解决方法

Node实现了ECMAScript 5,它有 Function.bind().

我认为这就是你要找的东西.

exports.Handlers.prototype.getItemById = function(id) {
    var item = this.db.getItemById(id,(function(error,item) {
        item.name = this.prefix + item.name;
        ...
        ...
    }).bind(this)); //bind context to function
};

这是有效的,但是当使用闭包作为回调时,就像你正在做的那样,最常见的方法是将上下文存储在可以在闭包中使用的变量中.

这种方法比较常见,因为很多次回调都很深,每次回调调用bind都很重;而定义自己一次很容易:

SomeObject.prototype.method = function(id,cb) {
    var self = this;
    this.getSomething(id,function(something) {
        //self is still in scope
        self.getSomethingElse(something.id,function(selse) {
            //self is still in scope and I didn't need to bind twice
            self.gotthemAll(selse.id,cb);
        });
    });
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐