javascript - JavaScript 模块的反射/自省
问题描述
假设我有:
// test.js
function myFunc(a,b,c) {
return "Test";
}
module.exports.myFunc = myFunc;
我怎样才能动态地找出 test.js 有一个函数 myFunc ,它需要 3 个参数,所以:
x = require('test.js')
if ( x has function defined myFunc ) {
if ( function myFunc in x has 3 arguments) {
"OK"
} else { "Expect 3 params"}
} else {
"test.js does not expose myFunc" }
这可能使用反射/内省吗?
谢谢
解决方案
这不是特定于模块的。函数的数量可以通过length
JavaScript 中的属性来确定,myFunc.length === 3
.
在生产中依赖length
是一种矛盾的做法,通常会导致代码异味。在测试中,预期的length
行为可能是不受欢迎的。
不是很好:
function myFunc(...args) {
const [a,b,c] = args;
}
myFunc.length === 0;
一点都不好:
function myFunc(a, b = 1, c = 2) {}
myFunc.length === 1;
如果myFunc.length
期望在单元测试中使用,建议跳过此断言并专注于函数行为。
推荐阅读
- node.js - 如何使用 Javascript 使用 Cloud Functions 增加 Firestore 中的字段值?
- magento2 - Magento2.3 admin order view 自定义按钮展示表单
- python - 如何在 docker 容器中安装 python 模块
- flutter - 将flutter GetX与flutter_modular和flutter_hook混合
- reactjs - 错误:未定义所选字段(电子邮件)
- javascript - 在 ReactJS 中扩展功能组件
- c++ - 简单奥林匹克问题的贪心算法
- java - 由于某种原因,我的 Spring Boot 应用程序不理解 bcrypt
- python - 使用 python 纸浆创建优化问题以最小化两个求和
- python - KeyError:使用会话时 Docker 中的“电子邮件”