Express:将 res.json 作为参数传递时出错

pom*_*ber 1 javascript scope node.js express

我有这样的事情:

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

app.get('/someRoute', function (req, res) {
    someService(function (result) {
        res.json(result);
    });
});
...
Run Code Online (Sandbox Code Playgroud)

我想将获取更改为:

app.get('/someRoute', function (req, res) {
    someService(res.json);
});
Run Code Online (Sandbox Code Playgroud)

但它给了我:

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

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

fur*_*oid 5

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

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

您可以someService(res.json.bind(res));通过显式绑定thisres.

MDN 文章:

这个

函数.prototype.bind