首页 > 解决方案 > nodejs循环模块app结构

问题描述

我在以下结构中有 3 个文件:

  1. 根.js
  2. mod1.js
  3. mod2.js

mod1.js 和 mod2.js 在 root.js 中都是必需的/实例化的,并且 mod1.js 和 mod2.js 都是 require("root.js"); 这样我就可以对 root.js 中的公共函数执行回调......我遇到的问题是 const root = require("root.js"); 在 mod1.js 和 mod2.js 中都是 {} 或空对象。尤其是当我在 mod1 和 mod2 中添加更多代码时,它们最终都是 {}

可以在这里看到错误屏幕截图: https ://github.com/DarceyLloyd/NodeAppArchitecture/blob/master/issue.png

所以问题是,在实例化过程中,什么结构或什么代码正确地实现了每个类/函数/对象的返回?结构变化?我已经使用映射到主体的 keyup 函数对此进行了测试,因此当我按下 spac eit 时需要 root.js 然后运行它的 getA 函数就好了,但是它只在按键时这样做,所以在类/函数/对象实例化/创建。想法?

所有文件都可以在这里看到: https ://github.com/DarceyLloyd/NodeAppArchitecture

对于stackoverflow参考:

根.js

```` var Root = function(){ this.a = -1; 这个.b = -1;

const mod1 = require("./mod1.js"); // Runs 2nd?
const mod2 = require("./mod2.js"); // Runs 1st?

function init(){
    this.a = 0;
    this.b = 0;
}

this.incA = function() { this.a++; }
this.incB = function() { this.a++; }
this.getA = function() { return this.a; console.log(a); }
this.getB = function() { return this.b; console.log(b); }

init();

}

// 缓存输出,所以 new 只会被调用一次 module.exports = new Root(); ````

mod1.js

```` var Mod1 = function(){ const root = require("./root.js");

function init(){
    console.log("Mod1()");
    console.log(root); // result is {}
    //root.incA(); // error incA doesn't exist on object root
}

init();

}

// 缓存输出,所以 new 只会被调用一次 module.exports = new Mod1(); ````

mod2.js

```` var Mod2 = function(){ const root = require("./root.js");

function init(){
    console.log("Mod2()");
    console.log(root); // result is {}
    //root.incB(); // error incB doesn't exist on object root
}

init();

}

// 缓存输出,所以 new 只会被调用一次 module.exports = new Mod2(); ````

标签: javascriptnode.jsstructure

解决方案


通常循环依赖意味着缺乏架构,有一个耦合系统,所以,避免循环依赖总是好的。如果模块 A 使用模块 B 并且模块 B 使用模块 A (A -> B, B -> A) 那么这可能是同一个模块,或者甚至是一个选项试图拆分更多更小的功能以仅导入最少的功能。@Vitiok 提出的解决方案没关系,在 init 函数中需要模块。请记住,要求是同步的,如果您有一个网络应用程序,如果您多次使用此解决方案,这可能会冻结您的 CPU。

我的建议:如果您想避免真正难以调试的问题,请不要创建循环依赖项。


推荐阅读