【问题标题】:Node modules as constructor function节点模块作为构造函数
【发布时间】:2023-03-04 20:55:01
【问题描述】:

我正在开发我的第一个 NodeJS 项目。当我在书本和互联网上阅读时,我开始以经典的方式构建模块。 随着项目开始增长,我决定将模块拆分为可重复使用的小块。这导致我在文件顶部有很多require,有时还有处理循环依赖的风险。此外,这种方法并不真正适合测试,因为我必须要求所有依赖项才能进行测试。我向其他开发人员询问了解决此问题的更好方法,他们中的大多数人建议我将依赖注入与函数构造函数一起使用。

假设我有 ModuleA 和 ModuleB, ModuleC 需要 ModuleA 和 ModuleB。我应该将它们作为构造函数中的参数传递,而不是要求这些模块位于页面顶部。 例如

module.exports = function ModuleC(moduleA, moduleB) {
 //module implementation here....
 function doSomething() {}
 return {
   doSomething
 }
}

这种方法最初看起来不错的问题是,在应用程序的主入口点中,我必须要求并实例化所有模块才能通过。

const ModuleA = require("./moduleA");
const ModuleB = require("./moduleB");
const ModuleC = require("./moduleC");

const moduleA = new ModuleA();
const moduleB = new ModuleB();


const moduleC = new ModuleC(moduleA, moduleB);
moduleC.doSomething();

现在只有 3 个模块,我必须编写 7 行代码才能使用模块的功能。如果我有 20 个模块来处理应用程序的主入口点,那将是一场噩梦。

我想这不是最好的方法,即使使用这种方法,测试也不容易。

所以,在开始探索 NodeJS 词的同时,我请你建议/解释我完成这个简单任务的最佳方法,也许比现在更难。谢谢。

【问题讨论】:

    标签: node.js testing module


    【解决方案1】:

    如果您将所有代码放在一个文件中,也可以实现代码的可重用性。创建更小的模块并不是唯一的解决方案。考虑在文件allLogic.js(let) 中编写的以下代码。

    var allFunctions = function(){ };
    var allFunctionsProto = allFunctions.prototype;
    
    allFunctionsProto.getJSONFile = function(fileName){ 
        var that = this;    //use 'that' instead of 'this'
        //code to fetch json file
    };
    
    
    allFunctionsProto.calculateInterest = function(price){
        var that = this;    //use 'that' instead of 'this'
        //code to calculate interest
    };
    
    allFunctionsProto.sendResponse = function(data){
        var that = this;    //use 'that' instead of 'this'
        //code to send response
    };
    
    //similary write all of your functions here using "allFunctionsProto.<yourFunctionName>"
    
    module.exports = new allFunctions();
    

    每当我需要获取任何 JSON 文件时,我都知道获取 JSON 文件的逻辑已经写在 allLogic.js 文件中,因此我需要这个模块并使用它,如下所示。

    var allLogic = require('../path-to-allLogic/allLogic.js');
    allLogic.getJSON();
    

    这种方法比为每项工作创建大量模块要好得多。当然,如果模块变得更长,您可以创建新模块,但在这种情况下,您需要考虑关注点分离,否则循环依赖会困扰您。

    当您在moduleC 中使用moduleAmoduleB 时,如果您将模块A、模块B 和模块C 中的所有代码放在一个模块中,正如我所指出的,您可以引用这些函数和所有该模块中使用 that 的单独函数,这些函数在 require 之后也可用。

    【讨论】:

      猜你喜欢
      • 2016-02-15
      • 1970-01-01
      • 2019-05-13
      • 2015-02-06
      • 2021-10-15
      • 2019-09-24
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多