• @Wilberforce the constructor function isn't actually required as exports is normally just an object (but for most modules you would have one anyway so your method makes a lot of sense).

    The first bit of @Robin's code is a valid module:

    var C = {
      U : "up",
      D : "down",
      L : "left",
      R : "right",
      N : "north",
      E : "east",
      S : "south",
      W : "west",
      T : "top",
      M : "middle",
      B : "bottom"
    };
    exports = C;
    

    I'm not sure I understand the question @Robin but I think you're asking if you can reference one module from another one? Yes, you can.

    Assume you have the code above in one module https://github.com/.../C.js. The next module can be:

    var C = require("https://github.com/.../C.js");
    var GROUPS = {
      COMPASS   : [{N:C.N}, {E:C.E}, {S:C.S}, {W:C.W}],
    //  COMPASS   : [ C.N, C.E, C.S, C.W ],  
      DIRECTION : [ C.U, C.D, C.L, C.R ],
      VERTICAL  : [ C.T, C.M, C.B ]
    };
    exports = GROUPS;
    

    Then you can access both:

    var C = require("https://github.com/.../C.js");
    var GROUPS = require("https://github.com/.../GROUPS.j­s");
    print( C.S );
    print( GROUPS.COMPASS );
    print( GROUPS.COMPASS.E );
    

    OR: Maybe you just want both in one module? That's easy too:

    var exports={}; // you don't need this in the module itself. It's just when in the IDE
    var C = {
      U : "up",
      D : "down",
      L : "left",
      R : "right",
      N : "north",
      E : "east",
      S : "south",
      W : "west",
      T : "top",
      M : "middle",
      B : "bottom"
    };
    exports.C = C; //<------------------------------- Note the added '.C'
    var GROUPS = {
      COMPASS   : [{N:C.N}, {E:C.E}, {S:C.S}, {W:C.W}],
    //  COMPASS   : [ C.N, C.E, C.S, C.W ],  
      DIRECTION : [ C.U, C.D, C.L, C.R ],
      VERTICAL  : [ C.T, C.M, C.B ]
    };
    exports.GROUPS = GROUPS; //<------------------------------- Note the added '.GROUPS'
    

    Now you can use it like:

    var module = require(" ... ");
    print( module.C.S );
    print( module.GROUPS.COMPASS );
    print( module.GROUPS.COMPASS.E );
    

    or

    var module = require(" ... ");
    var C = module.C;
    var GROUPS = module.GROUPS;
    print( C.S );
    print( GROUPS.COMPASS );
    print( GROUPS.COMPASS.E );
    
About

Avatar for Gordon @Gordon started