0

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
handle
  • 5,859
  • 3
  • 54
  • 82
  • 3
    "*Is there a way to keep a static count*" - yes, but then you need to refer to the `static` property [using `Myclass.s`, not `this.s`](https://stackoverflow.com/a/28648214/1048572). "*or are the instances better tracked outside the class*" - yes, absolutely! You shouldn't even push them from the constructor into that array, but use a separate factory function. – Bergi Jun 29 '22 at 15:06

1 Answers1

2

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)
Phillip
  • 6,033
  • 3
  • 24
  • 34