快速:错误传递res.json作为参数

我有这样的东西:

... var someService = function(next) { var result = {"some": "json"}; next(result); }; app.get('/someRoute', function (req, res) { someService(function (result) { res.json(result); }); }); ... 

我想改变这个:

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

但它给了我:

TypeError:无法在某个服务上调用res.json(… / node_modules / express / lib / response.js:185:22)处未定义的方法“get”

我想这个问题是关于范围的。 它是什么?

这个问题似乎是JavaScript中的方法范围受到语法上的约束。

在res.json方法里面,它引用了this 。 当像res.json(/* some arg */)那样res.json(/* some arg */)this值就是res 。 当你传递res.json作为callback时,像someService(res.json);this不再是res

你可以把它someService(res.json.bind(res)); 得到你想要的结果,通过显式绑定到res

MDN文章:

这个

Function.prototype.bind