我正在使用Express v3.4.4.当我尝试这样做时:
var cb = res.send;
cb(result);
我收到一个错误:
...\node_modules\express\lib\response.js:84
var HEAD = 'HEAD' == req.method;
TypeError: Cannot read property 'method' of undefined
在代码中,工作一个:
workflow.on('someEvent', function () {
res.send({
error: null,
result: 'Result'
});
});
不工作:
workflow.on('someEvent', function () {
var cb = res.send;
cb({
error: null,
result: 'Result'
});
});
最佳答案:
发送实际上是对象res的功能.它尝试使用res对象中的其他数据.但是,当你这样做的时候
var cb = res.send;
cb({...});
你只是使用函数对象发送而不引用res对象.这就是为什么它不起作用.
如果您需要执行类似的操作,请将res对象绑定到send函数,如下所示
var cb = res.send.bind(res);
现在
cb({...});
也会工作.因为res绑定到send函数对象,结果函数存储在cb中.
绑定功能实际上是Function.prototype.bind