Jared Murphy Jared Murphy -4 years ago 119
Javascript Question

ES6 Classes - Updating Static Properties

thanks for taking a look at this. I am trying to figure out alternative ways to set a static (or class) property an ES6 Class and then change it after new instances of the class are created.

For example - Lets say I have a class called Geo, and I need a static property called 'all' that will give me the array of all instances of the Geo class.

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); // => 2


I would prefer to not set the property OUTSIDE of the class definition though. I've tried a few things but can't seem to create a static property within the class that I can update from the constructor.

I should also mention I need to be able to do this in the browser (Chrome) without use of Babel or similar.

Here are examples of some things I've 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); // => 0


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); // => error unexpected "="


Any help would be greatly appreciated, thanks!

Answer Source

There's no such thing as static all = [] in ES6. Class fields are stage 2 proposal, which can be used via a transpiler, e.g. Babel.

Geo.all = [];

is valid and preferable way to do this in ES6. The alternative is getter/setter pair - or only a getter for read-only property:

class Geo {
  static get all() {
    if (!this._all)
      this._all = [];

    return this._all;
  }

  constructor() { ... }
}

Tracking instances in static property can't generally be considered a good pattern and will lead to uncontrollable memory consumption and leaks (as it was mentioned in comments).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download