javascript - js中this指向的问题
巴扎黑
巴扎黑 2017-04-11 12:38:53
[JavaScript讨论组]

这样写是可以正常调用的

router.route('/account')
.get(function (req, res, next) {
    User.find()
    .then(users => res.json(users))
    .catch(err => next(err));
});

我觉得这段代码可以简化成

router.route('/account')
.get(function (req, res, next) {
    User.find()
    .then(res.json)
    .catch(next);
});

可是采用第二种写法的时候在express的源码中会报错

res.json = function json(obj) {
  var val = obj;

  // allow status / body
  if (arguments.length === 2) {
    // res.json(body, status) backwards compat
    if (typeof arguments[1] === 'number') {
      deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');
      this.statusCode = arguments[1];
    } else {
      deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');
      this.statusCode = arguments[0];
      val = arguments[1];
    }
  }

  // settings
  var app = this.app;
  var replacer = app.get('json replacer');
  var spaces = app.get('json spaces');
  var body = JSON.stringify(val, replacer, spaces);

  // content-type
  if (!this.get('Content-Type')) {
    this.set('Content-Type', 'application/json');
  }

  return this.send(body);
};

就是在

var app = this.app;

这一行,debug发现this值是undefined,在js里面,对象的方法,this不是应该直接指向该对象吗?为什么这里this也就是res会是undefined呢?

巴扎黑
巴扎黑

全部回复(1)
PHPz
router.route('/account')
.get(function (req, res, next) {
    User.find()
    .then(res.json.bind(res))//这样this就指向res了
    .catch(next);
});
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号