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;
...
}
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;
...
}
Share
Improve this question
asked May 12, 2019 at 20:24
TheCatTheCat
7571 gold badge12 silver badges24 bronze badges
2
- 1 Use a class variable rather than a global variable, and increment it in the constructor. – Barmar Commented May 12, 2019 at 20:27
-
Just exchange
window
for a better suited object… And no need to make it a global variable, any variable outside the constructor scope will suffice. – Bergi Commented May 12, 2019 at 20:30
4 Answers
Reset to default 5You can use static
property and increase it in the constructor()
class MyClass{
static count = 0;
constructor(){
this.instanceId = ++MyClass.count;
}
}
let x = new MyClass();
let y = new MyClass();
console.log(MyClass.count) //2
console.log(x.instanceId); //1
console.log(y.instanceId); //2
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());
It's not necessary for the property to be in the global scope:
class MyClass {
static count = 0;
instanceId = MyClass.count++;
}
Yes, you can easily simplify class instances.
class Test {
constructor() {
this.a = 10;
this.b = 20;
}
m1() {
this.c = 30;
}
}
let obj = new Test()
count = Object.keys(obj).length;
console.log(count) //-------------------2
obj.m1();
count = Object.keys(obj).length;
console.log(count) //-------------------3
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744371965a4570998.html
评论列表(0条)