gpt4 book ai didi

javascript - JavaScript 模块的反射/内省(introspection)

转载 作者:行者123 更新时间:2023-12-03 01:18:07 28 4
gpt4 key购买 nike

假设我有:

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

使用反射/内省(introspection)可以实现这一点吗?

谢谢

最佳答案

这不是特定于模块的。函数数量可以通过 JavaScript 中的 length 属性来确定,myFunc.length === 3

在生产中依赖长度是一种矛盾的做法,通常会导致代码异味。在测试中,预期的length行为可能并不理想。

不太好:

function myFunc(...args) {
const [a,b,c] = args;
}

myFunc.length === 0;

一点都不好:

function myFunc(a, b = 1, c = 2) {}

myFunc.length === 1;

如果预计在单元测试中使用 myFunc.length,建议跳过此断言并专注于函数行为。

关于javascript - JavaScript 模块的反射/内省(introspection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51902559/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com