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

查看:123
本文介绍了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 is req, which is a stream

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

这篇关于node.js - node 回调函数中 var temp = this 的意义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆