I need to keep track of how many instances of a class have been created, from within the said class. I need every instance natively to know 'which one' it is.
The only way I could think of was to use global variables but... there may be a better way.
Here is what I want to avoid:
class MyClass {
this.instanceId = (window.instanceCount == undefined) ? 0 : window.instanceCount + 1;
window.instanceCount = this.instanceId;
...
}
You can statically add a counter to your "class". Here I use a symbol to prevent names collision. Note that I check whether you use Burrito
as a function or a class prior to incrementing the counter.
function Burrito() {
if (this instanceof Burrito) {
Burrito[Burrito.counterName]++;
}
}
Burrito.counterName = Symbol();
Burrito[Burrito.counterName] = 0;
Burrito.count = () => Burrito[Burrito.counterName];
new Burrito(); // 1
new Burrito(); // 2
Burrito(); // skipped
new Burrito(); // 3
console.log(Burrito.count());