背景: 基于这个关于 how to expose a library for unit testing with Jest 的问题.我现在想创建一类可以在点符号内使用点符号调用的函数(这甚至不可能)。首先是我目前使用的一些方法:
这是我如何修改 JavaScript 数学函数的示例:
Math.mean = function(numericArray){
if(Math.isNumericArray(numericArray)){
return math.mean(numericArray);
}
return false;
}
仅供引用,小写的 math.mean() 调用是对数学库的调用:https://mathjs.org/ , isNumericArray 只是一个验证器,用于确保传入的是一个数值数组。
然后我像这样导出它:
module.exports.mean = exports = Math.mean;
所以 Jest 可以在我的单元测试中看到它。
我的实际问题: 我想要做的是创建一个名为 Math.acs 的上层“类”,因此您可以使用 Math.acs 调用它。然后它会有子函数(例如:foo() & bar())所以你可以这样调用它们:Math.acs.foo(data);或 Math.acs.bar(数据);
我试过 encapsulate them into an IIFE :
Math.acs = (function(data) {
function foo(data){
console.log('hi mom');
};
function bar(data){
console.log("hi dad");
}
return bar;
})();
这没有用(CLI 在 Math.acs 下看不到任何东西),我还尝试了函数内部的直接函数,但也没有用。
如果这不可能,我不会去死,但它会让 acs 模块中所需的六个左右的功能集中起来,并且更容易维护。如果不可能,我可以按照上面显示的方式编写各个数学模块。
最佳答案
您需要获取一个具有属性的函数并返回该函数。
Math.acs = (function(data) {
function f() {};
f.foo = function (data) { console.log('hi mom'); };
f.bar = function (data) { console.log("hi dad"); };
return f;
})();
关于javascript - 创建可以通过点符号调用的子函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55857281/