How to deal with cyclic dependencies in Node.js

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

    You can solve this easily: just export your data before you require anything else in modules where you use 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();
    

提交回复
热议问题