需要时初始化模块 [英] Initialize a module when it's required

查看:53
本文介绍了需要时初始化模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些初始化代码的模块.加载模块时应执行初始化.此刻,我正在这样做:

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')

init应该返回什么,以保持mod引用正常工作?

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

推荐答案

您可以返回this,在这种情况下,它是对exports的引用.

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'

这篇关于需要时初始化模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆