简体   繁体   English

创建可以用点表示法调用的子函数

[英]Create sub functions that can be called by dot notation

Background: Building on this question about how to expose a library for unit testing with Jest . 背景:基于关于如何公开Jest进行单元测试的库的问题。 I would now like to create a class of functions that can be called with dot notation inside of dot notation ( this may not even be possible ). 现在,我想创建一个可以在点表示法内用点表示法调用的函数类( 这甚至是不可能的 )。 First a bit of methodology that I'm currently using: 首先,我正在使用一些方法:

Here's an example of how I've been modifying the JavaScript Math functions: 这是我如何修改JavaScript Math函数的示例:

Math.mean = function(numericArray){
    if(Math.isNumericArray(numericArray)){
        return math.mean(numericArray);
    }
    return false;
}

FYI, The lowercase math.mean() call is to the math library: https://mathjs.org/ , and isNumericArray is just a validator to make sure what's passed in is a numeric array. 仅供参考,小写的math.mean()调用是对数学库的: https ://mathjs.org/,isNumericArray只是一个验证器,以确保传入的是数字数组。

And then I export it like this: 然后我将其导出为:

module.exports.mean = exports = Math.mean;

So Jest can see it for my unit tests. 因此Jest可以在我的单元测试中看到它。

My actual question: What I want to do is create an upper level "class" called Math.acs, so you'd make the call into it with Math.acs. 我的实际问题:我想做的是创建一个名为Math.acs的上层“类”,因此您可以使用Math.acs对其进行调用。 Then it would have sub-functions (EG: foo() & bar()) so you'd call them like this: Math.acs.foo(data); 然后它将具有子功能(例如:foo()和bar()),因此您可以这样称呼它们:Math.acs.foo(data); or Math.acs.bar(data); 或Math.acs.bar(data);

I've tried to encapsulate them into an IIFE : 我试图将它们封装到IIFE中

Math.acs = (function(data) {
    function foo(data){
        console.log('hi mom');
    };
    function bar(data){
        console.log("hi dad");
    }
    return bar;
})();

Which didn't work (the CLI can't see anything below Math.acs), I've also tried straight functions inside of functions which also didn't work. 哪个不起作用(CLI在Math.acs之下看不到任何东西),我还尝试了在不起作用的函数内部使用直接函数。

I'm not going to die if this isn't possible, but it would make the half dozen or so functions required in the acs module centralized and easier to maintain. 如果这不可能的话,我不会死,但是它将使acs模块中所需的一半左右功能集中并且易于维护。 If it's not possible, I can write the individual math modules the same way I've shown above. 如果不可能,我可以按照上面显示的方式编写各个数学模块。

You need to take a function with properties and return this function. 您需要使用带有属性的函数并返回此函数。

Math.acs = (function(data) {
    function f() {};
    f.foo = function (data) { console.log('hi mom'); };
    f.bar = function (data) { console.log("hi dad"); };
    return f;
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM