You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript async函数闭包中通过字符串检查函数存在性

在Async函数中检查闭包内的函数是否存在(字符串变量形式)

我在JavaScript的async function里碰到了个小难题:需要检查某个函数是否在闭包环境中可用。这个函数确实存在,我可以直接调用它,也能通过console.log(myClosureScopedFunc)看到它的内容,但如果函数名是存在字符串变量里的,该怎么检查它是否在闭包中呢?

我试过几种思路,但都有局限:

  • 在async function中,this的值是undefined,不然我还能通过if (this['myClosureScopedFunc'])来做检查
  • 出于一些明显的原因,我没法在myClosureScopedFunc的同一作用域里执行self = this,因为在async function里self同样会是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"
}

解决方案

由于这个问题被标记为半相关案例的重复,我特意把解决方案补充在这里,方便搜索到的用户查看。以下是Node.js module环境中的具体实现方法:

我最初的第二个思路(也就是上面提到的self = this的想法)其实是正确的,但正如评论者@Bergi指出的,this关键字是用来限定方法作用域的。

所以正确的做法是把每个函数添加到exports对象中,之后就能按预期使用了:

'use strict'
const self = this // 绑定模块作用域
exports.myClosureScopedFunc = myClosureScopedFunc // 将函数添加到作用域

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"
}

内容的提问来源于stack exchange,提问作者Redsandro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:03:44