我最近一直在使用nodejs,仍然在掌握模块系统,所以如果这是一个明显的问题,那么很抱歉。我希望代码大致如下:
A.js(主文件与node一起运行)
var ClassB = require("./b");
var ClassA = function() {
this.thing = new ClassB();
this.property = 5;
}
var a = new ClassA();
module.exports = a;
b.js
var a = require("./a");
var ClassB = function() {
}
ClassB.prototype.doSomethingLater() {
util.log(a.property);
}
module.exports = ClassB;
我的问题似乎是我不能从ClassB的实例中访问ClassA的实例。
有什么正确的/更好的方法来构建模块来实现我想要的?
是否有更好的方法在模块间共享变量?
现在不是2015年,大多数库(例如express)已经更新了更好的模式,因此不再需要循环依赖。我建议不要使用它们。
我知道我挖出了一个老答案……
这里的问题是这个模块。exports定义在您需要ClassB之后。
(JohnnyHK的链接显示)
循环依赖关系在Node中工作得很好,它们是同步定义的。
如果使用得当,它们实际上解决了许多常见的节点问题(比如从其他文件访问express.js应用程序)
只需确保在需要具有循环依赖关系的文件之前定义了必要的导出。
这将打破:
var ClassA = function(){};
var ClassB = require('classB'); //will require ClassA, which has no exports yet
module.exports = ClassA;
这是可行的:
var ClassA = module.exports = function(){};
var ClassB = require('classB');
我一直使用这个模式来访问其他文件中的express.js应用程序:
var express = require('express');
var app = module.exports = express();
// load in other dependencies, which can now require this file and use app
你可以很容易地解决这个问题:在你需要使用module.exports的模块中任何其他东西之前,只需导出你的数据:
classA.js
class ClassA {
constructor(){
ClassB.someMethod();
ClassB.anotherMethod();
};
static someMethod () {
console.log( 'Class A Doing someMethod' );
};
static anotherMethod () {
console.log( 'Class A Doing anotherMethod' );
};
};
module.exports = ClassA;
var ClassB = require( "./classB.js" );
let classX = new ClassA();
classB.js
class ClassB {
constructor(){
ClassA.someMethod();
ClassA.anotherMethod();
};
static someMethod () {
console.log( 'Class B Doing someMethod' );
};
static anotherMethod () {
console.log( 'Class A Doing anotherMethod' );
};
};
module.exports = ClassB;
var ClassA = require( "./classA.js" );
let classX = new ClassB();