//FANCYLOGGER.JS!
class FancyLogger {
constructor() { //only ever create just one instance of this class...
if (FancyLogger.instance == null) {
this.logs = []
FancyLogger.instance = this /*"this" returns the current instance that was created the first
time the code ran*/
}
return FancyLogger.instance
}
log(message) {
this.logs.push(message)
console.log(`FANCY: ${message}`)
}
printLogCount() {
console.log(`${this.logs.length} Logs`)
}
}
const logger = new FancyLogger() //this is the actual single instance of FancyLogger
Object.freeze(logger) //freeze() prohibits any changes to this single instance by our code
export default logger //export the instance of the logger variable, not the class file
//(keep it Singleton)
//FIRSTUSE.JS
import logger from './fancyLogger.js' //not importing the class, only the one instance we created
export default function logFirstImplementation() {
logger.printLogCount() //where ever we see the "logger" reference we're calling the imported instance
logger.log('First File')
logger.printLogCount()
}
//SECONDUSE.JS
import logger from './fancyLogger.js' //not importing the class, only the one instance we created
export default function logFirstImplementation() {
logger.printLogCount() //where ever we see the "logger" reference we're calling the imported instance
logger.log('Second File')
logger.printLogCount()
}
//INDEX.JS
import logFirstImplementation from './firstUse.js'
import logSecondImplementation from './secondUse.js'
logFirstImplementation() //call the method from the imported file
logSecondImplementation() //call the method from the imported file