使用逻辑或运算符 (a || b) 到 运行 JS 中两个函数之一

using logical OR operator (a || b) to run one of two function in JS

为什么我只能使用三元运算符调用两个函数之一?

我想做什么:

newToken(account, request, response, returning = false) {
  /* Irrelevant code ommitted */
    return Promise.resolve((returning || response.json)({message: 'ok', account}))
}

以上使用逻辑 OR 运算符来 select returning 函数(如果可用)否则只需设置 json 响应

然而,当我以这种方式设置代码时,出现错误:Cannot read 'app' of undefined

如果我改用三元,代码工作正常:

newToken(account, request, response, returning = false) {
  /* Irrelevant code ommitted */
    return Promise.resolve(returning ? returning({message: 'ok', account}) : response.json({message: 'ok', account}))
}

如果我只是 运行 console.log((returning || response.json)) 总是记录正确的功能,那么为什么我不能 运行 这样设置的功能?

response.json(...)
函数内部的

this等于response.

的值

当你使用OR版本时,相当于:

tempfn = returning || response.json;
tempfn({message: 'ok', account});

调用 tempfn 不会将 this 变量绑定到任何东西,因此它默认为全局对象。

response.json 函数可能需要访问 response 对象,因此当您未正确绑定它时它会失败。

你可以通过显式调用.bind()得到你想要的:

newToken(account, request, response, returning = false) {
  /* Irrelevant code ommitted */
    return Promise.resolve((returning || response.json.bind(response))({message: 'ok', account}))
}