简体   繁体   English

从回调访问“ this”范围变量

[英]Accessing 'this' scope variable from callback

I am a javascript newbie, i have a problem with the following code. 我是javascript新手,以下代码有问题。 Am trying to set a price value from callback, but isn't working... Any help please? 我正在尝试通过回调设置价格值,但不起作用...请帮忙吗?

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

if i'm not mistaken, the closure gets the last value of j. 如果我没记错的话,闭包得到j的最后一个值。 so if the iteration runs from 0 to 3 then you always have self.work[3].workprice = 300; 因此,如果迭代从0到3进行,则您始终会有self.work [3] .workprice = 300; (try tracing). (尝试跟踪)。

try working with a library li lodash and turn you code into something like this: 尝试与li lidash图书馆合作,并将您的代码转换为如下形式:

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

also, if this is the real code then it's missing a '}' before the last ')'. 同样,如果这是真实的代码,则在最后一个')'之前缺少'}'。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM