I am trying to find alternative ways to set the static (or class) property of an ES6 class, and then change it after creating new instances of the class.
For example, let's say I have a class named Geo, and I need a static property called allthat will give me an array of all instances of the class Geo.
This version works:
class Geo {
constructor(name){
this.name = name;
Geo.all.push(this);
}
}
Geo.all = [];
ruby = new Geo("Ruby");
rocks = new Geo("Rocks");
console.log(Geo.all.length);
I would prefer not to set the property OUT of the class definition, though. I tried several things, but I canβt create a static property inside the class that I can update from the constructor.
I should also mention that I need to do this in a browser (Chrome) without using Babel or anything like that.
Here are some examples of the things I tried:
class Geo {
constructor(name){
this.name = name;
Geo.all.push(this);
}
static get all() {
return [];
}
}
ruby = new Geo("Ruby");
rocks = new Geo("Rocks");
console.log(Geo.all.length);
And another
class Geo {
constructor(name){
this.name = name;
Geo.all.push(this);
}
static all = [];
}
ruby = new Geo("Ruby");
rocks = new Geo("Rocks");
console.log(Geo.all.length);