【发布时间】:2026-01-12 08:20:02
【问题描述】:
在 JavaScript async function 中,我想检查某个函数在其闭包环境中是否可用。
该功能可用。我可以显式执行它,或者执行console.log(myClosureScopedFunc)。
但是当函数名在字符串变量中时,如何查看它是否存在于闭包中?
- 在
async function中,this是未定义的,否则我可以做if (this['myClosureScopedFunc']) // gotcha - 由于某些可能显而易见的原因,我也不能在与
myClosureScopedFunc相同的范围内执行self = this,因为self在async function中也是undefined。 -
eval('myClosureScopedFunc')有效,但出于某种原因我不想使用eval。
简约 express 代码示例
路由(要查找的函数)在req.params.route 中定义。
'use strict'
module.exports = async function(req, res, next) {
try {
if (this[req.params.route].length === 3) // THIS DOES NOT WORK
return await this[req.params.route](req, res, next)
}
catch(err) {
console.log(err.stack)
return res.status(404).end(err.message)
}
}
async function myClosureScopedFunc(req, res, next) {
return await "some async data"
}
这就是答案
对问题进行了编辑,因为它作为一个半相关案例的副本被关闭。万一有人通过 google 来到这里,您可以在 Node.js module 上下文中具体执行此操作。
我最初的第二个想法(上面的第二点)是正确的,但正如评论者 @Bergi 指出的那样,this 关键字作用域方法。
所以每个函数都需要添加到exports 对象中。然后我们就可以按预期使用它了:
'use strict'
const self = this // scope the module
exports.myClosureScopedFunc = myClosureScopedFunc // Add to scope
module.exports = async function(req, res, next) {
try {
if (self[req.params.route].length === 3)
return await self[req.params.route](req, res, next)
}
catch(err) {
console.log(err.stack)
return res.status(404).end(err.message)
}
}
async function myClosureScopedFunc(req, res, next) {
return await "some async data"
}
【问题讨论】:
-
我看不出这与
async/await有什么关系。在普通函数中也是如此。 -
JS 使用词法作用域。您不必检查它在运行时是否可用。您在编译时(和实施期间)就知道它是否在范围内!你的actual problem 是什么?听起来您确实在寻找
eval,所以请说明您想要的东西与eval有何不同。 -
@Bergi 你是对的。它在非异步中也不可用。我误判了。为什么这个函数里没有
this? -
this在async functions 中与普通functions 相比也没有什么特别之处。如果this不是您期望的值,则您没有将函数作为方法调用。 -
谢谢@Bergi,你帮我找到了答案。我已经在上面添加了;由于问题已锁定,我无法将其发布为答案。
标签: javascript node.js closures