const Formatter = (function() {
let timesRun = 0;
const log = (message) => console.log(`[${Date.now()}] Logger: ${message}`);
const setTimesRun = () => {
log("Setting times run");
++timesRun;
console.log(timesRun);
}
const makeUppercase = (text) => {
log("Making uppercase");
setTimesRun();
return text.toUpperCase();
};
return {
makeUppercase,
timesRun,
}
})()
console.log(Formatter.makeUppercase("tomek"));
console.log(Formatter.timesRun);
console.log(Formatter.makeUppercase("foo"));
console.log(Formatter.timesRun);
console.log(Formatter.makeUppercase("hey"));
console.log(Formatter.timesRun);
With console.log(Formatter.timesRun); I'm expecting the incremented value of timesRun. However, it keeps logging 0. Using console.log(timesRun); inside the setRimesRun() function logs the incremented value. I don't understand where the data is stored and why am I getting 0.
I thought timesRun was always 0 and I added console.log(timesRun); to test it. It showed the incremeneted value which confused the me even more.
The variable
timesRunis locally in the methodsetTimesRun. You should use the one outside ofsetTimesRun, soFormatter.timesRun.You can do like that:
Here, all times I'm using the same variable:
Formatter.timesRun. With this, all logger use the same and will some same instance of this int