How to deal with cyclic dependencies in Node.js

I’ve been working with nodejs lately and still getting to grips with the module system so apologies if this is an obvious question. I want code roughly like the following below:

a.js (the main file run with 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;

My problem seems to be that I can’t access the instance of ClassA from within an instance of ClassB.

Is there a correct / better way to structure modules to achieve what I want?
Is there a better way to share variables between modules?

16 Answers
16

Leave a Comment