从回调中访问'this'范围变量

时间:2013-06-16 20:58:21

标签: javascript node.js callback mongoose

我是一个javascript新手,我有以下代码的问题。我试图通过回调设置价格值,但是没有用......请帮忙吗?

PreInvoiceSchema.pre('save', function(next) {

//Seperating code from state
var codestate = addr[2].split(/[ ,]+/);
this.customer.zipcode = codestate[2];
this.customer.state = codestate[1];

//Calculating base price
if (this.order_subtype == "Upgrade") {
    this.price = 30;
} else {
    this.price = 50;
}
var self = this;

for (var j = 0; j < this.work.length; j++) {

    Price.findOne({
        "item": self.work[j].workproduct
    }, function(err, val) {
        if (self.work[j] != undefined) {
             self.work[j].workprice = 300; <-- this doesn't work
        }
    });
});

3 个答案:

答案 0 :(得分:0)

如果我没有弄错,闭包会得到j的最后一个值。因此,如果迭代从0到3运行,那么你总是有自己的工作[3] .workprice = 300; (尝试追踪)。

尝试使用库li lodash并将代码转换为以下内容:

_.each(this.work, function(item) {
    Price.findOne(
        { "item": item.workproduct }, 
        function(err, val) {
            // item.workprice ...
        }
    );
});

另外,如果这是真正的代码,那么它在最后一个')'之前缺少'}'。

答案 1 :(得分:0)

for (var j = 0; j < this.work.length; j++) {
    (function(i) {
        Price.findOne({
            "item": self.work[i].workproduct
        }, function(err, val) {
            if (self.work[i] != undefined) {
                 self.work[i].workprice = 300; <-- this doesn't work
            }
        });
    })(j);
});

答案 2 :(得分:0)

回顾文档,我也试过,在_.each

上传递上下文变量
_.each(this.work, function(item) {
    Price.findOne({
        "item": item.workproduct
    }, function(err, val) {
        item.workprice = 100;
    });
}, this); <-- passing 'context' 

但是还没有赋值......