1

I've been running into this issue lately and am looking for a good solution. Below is the basic setup.

In c.js, a is an empty object. Currently I got around this by putting the var a=require('./a.js') inside the function (cFunction) that needs access to module a's methods. But is that the best way to go about this?

Thanks, David


main.js

var a = require('./a.js');

a.js

module.exports = (function() {
    var b = require('./b.js');

    function aFunction() {
        console.log("aFunction");
    }

    return {
        aFunction: aFunction
    };

})();

b.js

module.exports = (function(){
    var c = require('./c.js');

    function bFunction(){
        console.log('bFunction');
    }

    return {
        bFunction: bFunction
    };

})();

c.js

module.exports = (function(){
    var a = require('./a.js');
    console.log(a); //empty object

    function cFunction(){
        a.aFunction(); //undefined
        console.log('cFunction');
    }

    return {
        cFunction: cFunction
    };

})();
David
  • 494
  • 1
  • 4
  • 11
  • Why are you using IIFEs at all? Modules already got their own scope. – Bergi Sep 02 '16 at 04:45
  • Possible duplicate of [How to deal with cyclic dependencies in Node.js](http://stackoverflow.com/questions/10869276/how-to-deal-with-cyclic-dependencies-in-node-js) – Tom Sep 02 '16 at 06:21
  • I read that already and many others, couldn't find a solution – David Sep 02 '16 at 06:24

0 Answers0