Module Definition Patterns (II)
Learn about exporting an instance and modifying other modules.
We'll cover the following...
Exporting an instance
We can leverage the caching mechanism of require()
to easily define stateful instances created from a constructor or a factory, which can be shared across different modules. The following code shows an example of this pattern:
Press + to interact
// file logger.jsclass Logger {constructor (name) {this.count = 0this.name = name}log (message) {this.count++console.log('[' + this.name + '] ' + message)}}module.exports = new Logger('DEFAULT')
This newly defined module can then be used as follows:
Press + to interact
// main.jsconst logger = require('./logger')logger.log('This is an informational message')
Because the module is cached, every module that requires the logger
module will actually always retrieve the same instance of the ...