首页 > 解决方案 > 通过字符串检查函数闭包中是否存在函数

问题描述

在 JavaScriptasync function中,我想检查某个函数在其闭包环境中是否可用。

该功能可用。我可以明确地执行它,或者做console.log(myClosureScopedFunc).

但是当函数的名称在字符串变量中时,如何查看它是否存在于闭包中?


简约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.jsmodule上下文中具体执行的方法。

我最初的第二个想法(上面的第二点)是正确的,但正如评论者@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"
}

标签: javascriptnode.jsclosures

解决方案


在模块上定义的函数不会暴露给global对象,因此要按名称访问这些函数,您需要将它们存储在对象中。

在下面的代码片段中,funcs定义了一个包含私有函数的对象,该对象不能从该模块外部访问,因为funcs它永远不会被导出。

function require() {

  const funcs = {
    async myClosureScopedFunc(req, res, next) {
      return await "some async data"
    }
  };
  
  // or
  // funcs.myClosureScopedFunc = async function(...) {}
  
  return async function exportedFunc(name) {
      if(funcs[name])
          console.log(await funcs[name]());
      else
        console.log('nop');
  }
}

const x = require();

x('imNotAFunction');
x('myClosureScopedFunc');


推荐阅读