【问题标题】:Express: Error passing res.json as parameterExpress:将 res.json 作为参数传递时出错
【发布时间】:2014-06-21 00:25:31
【问题描述】:

我有这样的事情:

...
var someService = function(next) {
    var result = {"some": "json"};
    next(result);
};

app.get('/someRoute', function (req, res) {
    someService(function (result) {
        res.json(result);
    });
});
...

我想把get改成这个:

app.get('/someRoute', function (req, res) {
    someService(res.json);
});

但它给了我:

TypeError:无法在 res.json 调用未定义的方法“get” (.../node_modules/express/lib/response.js:185:22) 在 someService

我想问题出在范围上。这是什么?

【问题讨论】:

    标签: javascript node.js express scope


    【解决方案1】:

    问题似乎是 Javascript 中方法的范围在语法上是绑定的。

    在 res.json 方法中,它引用了this。当像 res.json(/* some arg */) 一样调用时,this 的计算结果为 res。当您将res.json 作为回调传入时,例如someService(res.json);this 不再绑定到res

    您可以通过将this 显式绑定到res 将其更改为someService(res.json.bind(res)); 以获得所需的结果。

    MDN 文章:

    this

    Function.prototype.bind

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多