24

I have a module with some initialization code inside. The init should be performed when the module is loaded. At the moment I'm doing it like this:

 // in the module

 exports.init = function(config) { do it }

 // in main

 var mod = require('myModule');
 mod.init(myConfig)

That works, but I'd like to be more concise:

 var mod = require('myModule').init('myConfig')

What should init return in order to keep mod reference working?

georg
  • 204,715
  • 48
  • 286
  • 369

1 Answers1

46

You can return this, which is a reference to exports in this case.

exports.init = function(init) {
    console.log(init);
    return this;
};

exports.myMethod = function() {
    console.log('Has access to this');
}
var mod = require('./module.js').init('test'); //Prints 'test'

mod.myMethod(); //Will print 'Has access to this.'

Or you could use a constructor:

module.exports = function(config) {
    this.config = config;

    this.myMethod = function() {
        console.log('Has access to this');
    };
    return this;
};
var myModule = require('./module.js')(config);

myModule.myMethod(); //Prints 'Has access to this'
Ben Fortune
  • 30,323
  • 10
  • 77
  • 78