How to deal with cyclic dependencies in Node.js

后端 未结 13 1947
别那么骄傲
别那么骄傲 2020-11-22 04:36

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 b

13条回答
  •  终归单人心
    2020-11-22 05:00

    Sometimes it is really artificial to introduce a third class (as JohnnyHK advises), so in addition to Ianzz: If you do want to replace the module.exports, for example if you're creating a class (like the b.js file in the above example), this is possible as well, just make sure that in the file that is starting the circular require, the 'module.exports = ...' statement happens before the require statement.

    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 ClassB = function() {
    }
    
    ClassB.prototype.doSomethingLater() {
        util.log(a.property);
    }
    
    module.exports = ClassB;
    
    var a = require("./a"); // <------ this is the only necessary change
    

提交回复
热议问题