Home > Blockchain >  Static count of JavaScript Class instances
Static count of JavaScript Class instances

Time:06-30

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

CodePudding user response:

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)

  • Related