Can node modules require each other

前端 未结 3 1468
醉酒成梦
醉酒成梦 2020-12-24 06:14

I\'m having the following 3 files.

user.js requires room.js and room.js requires user.js.

user.js

var Room = require(\'./room.js\');

var Use         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 06:52

    The difference between:

    /* code above */
    function a() {};
    

    and

    /* code above */
    var a = function () {};
    

    Is that in the first example a will be function already in the code above, but not in the second example.

    Once you understand that you can come to this simple solution:

    // user.js

    module.exports = User;
    
    function User() {};
    User.prototype.test = function () {
      var Room = require('./room');
      return new Room();
    };
    

    // room.js

    module.exports = Room;
    
    function Room() {};
    Room.prototype.test = function () {
      var User = require('./user');
      return new User();
    };
    

    // index.js

    var User = require('./user.js');
    var Room = require('./room.js');
    
    var user = new User(Room);
    var room = new Room(User);
    

提交回复
热议问题