最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a way to count instances from a class? - Stack Overflow

programmeradmin7浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 5

You 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
发布评论

评论列表(0)

  1. 暂无评论