ES6 Classes - Updating Static Properties

后端 未结 3 814
再見小時候
再見小時候 2020-12-06 00:58

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 exa

3条回答
  •  囚心锁ツ
    2020-12-06 01:40

    There's no such thing as static all = [] in ES6. Class instance and static fields are currently stage 3 proposals which can be used via a transpiler, e.g. Babel. There's already existing implementation in TypeScript that may be incompatible with these proposals in some way, yet static all = [] is valid in TS and ES.Next.

    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).

提交回复
热议问题