我在以下结构中有3个文件:
在root.js中,mod1.js和mod2.js都是必需的/实例化的,而mod1.js和mod2.js都需要(“root.js”);所以我可以在root.js中执行对公共函数的回调。我遇到的问题是const = require("root.js");在mod1.js和mod2.js中都是{}或空对象。特别是当我在mod1和mod2中放入更多的代码时,它们最终都是{}
错误屏幕截图可以在这里看到:https://github.com/DarceyLloyd/NodeAppArchitecture/blob/master/issue.png
所以问题是,在实例化过程中,什么结构或什么代码正确地实现了每个类/函数/对象的返回?结构变化?我已经用映射到主体的keyup函数对此进行了测试,这样当我按spac时需要root.js,然后运行它的getA函数就可以了,但是它只在keypress上这样做,所以在类/函数/对象实例化/创建过程中不会这样做。想法?
所有文件都可以在这里看到:https://github.com/DarceyLloyd/NodeAppArchitecture
对于堆栈溢出引用:
root.js
```javascript
mod1 =需要量(“./mod1.js”);//运行第二次?
mod2 =需要量(“./mod2.js”);//运行1?
函数init(){
this.a = 0;
this.b = 0;
}
this.incA =函数(){ this.a++;}
this.incB =函数(){ this.a++;}
this.getA =函数(){返回此.a;console.log(a);}
this.getB =函数(){返回此.b;console.log(b);}
init();
}
// Cached output so new only ever gets called once 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();
}
//缓存的输出,因此只有在module.exports =新的Mod1();之后才会调用
mod2.js
```javascript
函数init(){
console.log("Mod2()");
console.log(root); // result is {}
//root.incB(); // error incB doesn't exist on object root
}
init();
}
//缓存的输出,因此只有在module.exports =新的Mod2();之后才会调用
发布于 2018-06-09 10:09:58
很抱歉让您失望,但是只要您在应用程序中执行循环导入,就不会得到正确的“实例化”。为了达到正确的行为,你不应该以循环的方式导入。目前,您实例化一个对象,而另一个对象尚未实例化。我建议您使用以下解决方案来确保尝试访问的对象被实例化。
// ROOT
const mod1 = require("./mod1.js"); // Runs 2nd?
const mod2 = require("./mod2.js"); // Runs 1st?
var Root = function(){
this.a = -1;
this.b = -1;
this.init = function(){
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); }
}
// Cached output so new only ever gets called once
module.exports = new Root();
mod2.init()
mod1.init()
// MOD2
var Mod2 = function(){
this.init = function() {
const root = require("./root.js");
console.log("Mod2()");
root.init()
console.log(root); // result is {}
root.incB(); // error incB doesn't exist on object root
}
}
// Cached output so new only ever gets called once
module.exports = new Mod2;
// Mod1
var Mod1 = function(){
this.init = function() {
const root = require("./root.js");
root.init()
console.log("Mod1()");
console.log(root); // result is {}
root.incA(); // error incA doesn't exist on object root
}
}
// Cached output so new only ever gets called once
module.exports = new Mod1;
发布于 2018-06-09 10:23:24
通常,循环依赖意味着缺乏体系结构,有一个耦合系统,因此,它总是很好地避免循环依赖。如果模块A使用模块B和模块B使用模块A (A -> B,B -> A),那么这可能是同一个模块,甚至还有一个选项试图拆分更小的功能来导入最小的功能。建议的解决方案由@Vitiok‘The,需要模块中的init函数。请记住,需要同步,如果您有一个web应用程序,这可能会冻结您的cpu,如果你击中这个解决方案太多次。
我的建议是:如果您想避免很难调试的问题,请不要创建循环依赖关系。
https://stackoverflow.com/questions/50776765
复制相似问题