How to deal with cyclic dependencies in Node.js

后端 未结 13 1934
别那么骄傲
别那么骄傲 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:16

    What about lazy requiring only when you need to? So your b.js looks as follows

    var ClassB = function() {
    }
    ClassB.prototype.doSomethingLater() {
        var a = require("./a");    //a.js has finished by now
        util.log(a.property);
    }
    module.exports = ClassB;
    

    Of course it is good practice to put all require statements on top of the file. But there are occasions, where I forgive myself for picking something out of an otherwise unrelated module. Call it a hack, but sometimes this is better than introducing a further dependency, or adding an extra module or adding new structures (EventEmitter, etc)

    0 讨论(0)
提交回复
热议问题