首页 > 解决方案 > 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" }

这可能使用反射/内省吗?

谢谢

标签: javascriptnode.jsmodule

解决方案


这不是特定于模块的。函数的数量可以通过lengthJavaScript 中的属性来确定,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期望在单元测试中使用,建议跳过此断言并专注于函数行为。


推荐阅读