javascript - 通过字符串检查函数闭包中是否存在函数
问题描述
在 JavaScriptasync function
中,我想检查某个函数在其闭包环境中是否可用。
该功能可用。我可以明确地执行它,或者做console.log(myClosureScopedFunc)
.
但是当函数的名称在字符串变量中时,如何查看它是否存在于闭包中?
- 在
async function
,this
中是未定义的,否则我可以这样做if (this['myClosureScopedFunc']) // gotcha
- 由于某些可能显而易见的原因,我不能
self = this
在与其中任何一个相同的范围内做myClosureScopedFunc
,因为self
也会undefined
在其中async function
。 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.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"
}
解决方案
在模块上定义的函数不会暴露给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');
推荐阅读
- php - 如何避免在 php 中的 URL 中重复路径?
- android - 如何使用 wrap 小部件在下一行设置分隔符?
- r - R中是否有修改自制函数的输入变量的方法?
- python - 无法使用 FastAPI 打开和读取上传的 zip 文件的内容
- python - 在 python 中四舍五入
- c# - 如何使用绑定将数据从 SQL 检索到文本框中?
- python - AttributeError: NDARRAY_SPEC 在导入 tensorflow 时
- amazon-web-services - 如何使无法访问互联网的EC2实例访问同一帐户中的资源?
- javascript - 发出套接字 io 事件时更改状态
- fullcalendar - 有没有办法在 Fullcalendar v5 resourceTimeline 视图上扩展上一个和下一个点击事件的资源?