Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Static count of JavaScript Class instances

Is there a way to keep a static count of instances along the lines of

class Myclass {
    static s = 0;       // static property
    p = 0;              // public field declaration
    constructor() {
        console.log("new instance!")
        this.s += 1;
        this.p += 1;
        console.log(this.s, this.p);
        this.i = this.s;    // instance property
    }
}

let a = new Myclass();
console.log(a.s, a.p, a.i)

let b = new Myclass();
console.log(b.s, b.p, b.i)

Output

new instance!
NaN 1
NaN 1 NaN
new instance!
NaN 1
NaN 1 NaN

or are the instances better tracked outside the class in e.g. an Array such as

var instances = new Array();

class Myclass {
    constructor(name) {
        console.log("new instance!")
        this.name = name;
        this.i = instances.length;
        instances.push(this);
    }
}

let a = new Myclass('a');
console.log(instances.length, a.i)

let b = new Myclass('b');
console.log(instances.length, b.i)

console.log( instances[1].name )

With the expected output

new instance!
1 0
new instance!
2 1
b
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Yes, you can use static but you cannot use this (as that refers to the specific instance). Instead use the classname.

class MyClass {
    static s = 0;       // static property
    p = 0;              // public field declaration
    constructor() {
        console.log("new instance!")
        MyClass.s += 1;
        this.p += 1;
        console.log(MyClass.s, this.p);
        this.i = MyClass.s;    // instance property
    }
}

let a = new MyClass();
console.log(MyClass.s, a.p, a.i)

let b = new MyClass();
console.log(MyClass.s, b.p, b.i)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!