2014-11-06 17 views
13

İçinde bazı başlatma kodu olan bir modül var. Modül yüklendiğinde init yapılmalıdır.Gerekli olduğunda bir modülü başlat

// in the module 

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

// in main 

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

O çalışır, ama daha özlü olmak istiyorum: Şu anda böyle yapıyorum

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

Ne sırayla init dönüş mod referans çalışmaya devam etmek gerekir?

cevap

22

Bu durumda exports referansı olan this'a dönebilirsiniz.

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

Ya bir kurucu kullanabilirsiniz:

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

Teşekkür ki yaradı! – georg

+0

yapıcı örneği çalışmıyor. Tüketici tarafı 'new' kullanmalısınız – alfredopacino

İlgili konular