Say I want to have a counter in a factory function that counts the number of objects that were made, I can do it as such:
function foo(){
// Factory code
this.counter = this.counter? this.counter + 1 : 1
console.log(this.counter)
}
let a = foo(); // Logs 1
let b = foo(); // Logs 2,
console.log(foo.counter) // undefined
What this shows, is that the counter property is being saved and edited on the foo function object. But foo.counter is undefined. So my question is:
Where is the property being saved and how can I access it?
>Solution :
You can add a static property to count
function foo(){
// Factory code
foo.counter = foo.counter? foo.counter + 1 : 1;
console.log(foo.counter)
}
let a = foo();
let b = foo();
console.log(foo.counter)
static property to count.