回调中的Javascript变量范围

Javascript variable scope inside callbacks

本文关键字:变量 范围 Javascript 回调      更新时间:2023-09-26

我使用的是formidable(github),我不确定回调中某些变量的范围。我的部分代码是:

UploadHandler.prototype.upload = function(req, res){
    var query = url.parse(req.url, true).query;
    var form = new formidable.IncomingForm();
    var id = query['X-Progress-ID'];
    self.uploads.add(id);
    form.parse(req, function(err, fields, files){
        self.uploads.remove(id);
        res.writeHead(200, { 'Content-type': 'text/plain' });
        return res.end('upload received');
    });
    ...
}

我的问题是,在parse的回调中,id的值是多少?此外,如果不止一个人在上传一个文件,该代码会像预期的那样工作吗?(如中所示,如果第一个人和第二个人同时使用上传器,id是否会更改其值。

id是您定义的,是的,如果对upload有多个调用,它就会起作用:id变量是upload函数调用的本地变量。这里的作用域是形成所谓闭包的函数调用。

以下是您代码的简化版本:

function upload(i){
   var id=i; // id is local to the invocation of upload
   setTimeout(function(){ console.log(id) }, 100*i);
}
for (var i=0; i<3; i++) {
    upload(i);
}

它记录0, 1, 2