Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading