我试图传递一个对象实例给其他对象。
Index.js
const A = require("./A.js");
A.getInstance().init();
A.js
const B = require("./B.js");
class A {
b;
instance;
static getInstance() {
if (this.instance == undefined)
this.instance = new A();
return this.instance;
}
init() {
this.b = new B();
}
test() {
console.log("Hello World!");
}
}
module.exports = A;
研究
const A = require("./A.js");
class B {
constructor() {
A.getInstance().test();
}
}
module.exports = B;
当我试图运行一个错误弹出说
a . getinstance()不是一个函数!
你有一个循环依赖。当两个模块相互需要时,就会发生这种情况。当A
试图导入B
时,模块B
试图导入A
,但模块A
尚未解决。这就是为什么会出现这个问题。
要解决这个问题,你需要做依赖注入。假设A
是这里最重要的模块。我们可以做的是从A
中导入B
,但在模块B
中添加一个方法,以便在模块A
准备好时传递依赖项。
A.js
const B = require("./B");
// Do your work here
const A = { /* Whatever here */ };
// Now pass the dependency to B
B.setA(A);
如果它仍然不能解决你的问题,那么你真的需要考虑项目的设计。如果代码高度相关,则将所有代码移到同一个文件中。