node.js - node 回调函数中 var temp = this 的意义
本文介绍了node.js - 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
。 是为了使得代码逻辑更加清晰吗? 还是有什么特殊的作用?
解决方案
看注释:
this
isreq
, which is a stream
此时this
指向req
,而req
对外可以当做是stream
来用,就只是变个名字,看起来更清楚点吧,没啥特殊意义。
这篇关于node.js - node 回调函数中 var temp = this 的意义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文