javascript - js中this指向的问题

 hushuoni_133 发布于 2022-11-09 21:16

这样写是可以正常调用的

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呢?

3 个回答
  • router.route('/account')
    .get(function (req, res, next) {
        User.find()
        .then(res.json.bind(res))//这样this就指向res了
        .catch(next);
    });
    2022-11-12 01:44 回答
  • function test1() {
        console.log(1, typeof(this));
    }
    
    function test2() {
        "use strict";
        console.log(2, typeof(this));
    }
    
    test1();
    test2();

    ES6 相当于是在 strict 模式下的

    在严格模式下,this 是在进入运行环境时设置的。若没有定义,this的值将维持undefined状态。同时它也能设置成任意值,比如 null 或者42 或者“I am not this”。

    参考:this - JavaScript | MDN

    2022-11-12 01:44 回答
  • 这两句不是等价的。。。。

    .then(users => res.json(users))
    .then(res.json)

    then 函数的实现大概是这样的

    function then(fn)
    {   //....
        fn(args);
    }

    所以其实二种写法分别是:

    var fn = function(users)
    {
        res.json(users)
    }
    fn(users);
    // 。。。。。
    fn = res.json;
    fn(users)

    这两种调用方式,在json函数里 this 的值是不同的。
    详见我的博客吧
    http://zonxin.github.io/post/...

    2022-11-12 01:44 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有