node 回调函数中 var temp = this 的意义

feedparser的示例中,我看到如下代码:


var request = require('request'); // for fetching the feed 
 
var req = request('http://somefeedurl.xml')
 
req.on('error', function (error) {
  // handle any request errors 
});
 
req.on('response', function (res) {
  var stream = this; // `this` is `req`, which is a stream 
 
  if (res.statusCode !== 200) {
    this.emit('error', new Error('Bad status code'));
  }
  else {
    stream.pipe(feedparser);
  }
});

令人疑惑的是,在此处的回调函数中,示例代码使用var stream = this。 是为了使得代码逻辑更加清晰吗? 还是有什么特殊的作用?

阅读 2.5k
2 个回答

看注释:

this is req, which is a stream

此时this指向req,而req对外可以当做是stream来用,就只是变个名字,看起来更清楚点吧,没啥特殊意义。

我只能说这个demo写得烂,不必迷信&过度揣测其用意。


正常的类似的写法是这样的

var xx = function() {
    var that = this;
    
    return funtion() {
        that.xxx
    }
}

可以在闭包里引用上层作用域的this

推荐问题