node.js 在需要时初始化模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26777705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize a module when it's required
提问by georg
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:
我有一个模块,里面有一些初始化代码。应该在加载模块时执行 init。目前我正在这样做:
// 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 initreturn in order to keep modreference working?
init为了保持mod参考工作,应该返回什么?
回答by Ben Fortune
You can return this, which is a reference to exportsin this case.
您可以 return this,exports在这种情况下它是对的引用。
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'

