Initialize a module when it's required

后端 未结 1 1488
梦如初夏
梦如初夏 2021-02-18 13:22

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 m         


        
相关标签:
1条回答
  • 2021-02-18 14:24

    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'
    
    0 讨论(0)
提交回复
热议问题