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
  • 211,518
  • 52
  • 313
  • 390

1 Answers1

47

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
  • 31,623
  • 10
  • 79
  • 80