ES6类 - 更新静态属性

Jar*_*red 15 javascript oop class object ecmascript-6

我试图找出将静态(或类)属性设置为ES6类的替代方法,然后在创建类的新实例后更改它.

例如,假设我有一个名为的类Geo,我需要一个名为的静态属性all,它将为我提供Geo该类所有实例的数组.

这个版本有效:

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
Run Code Online (Sandbox Code Playgroud)

我宁愿不设置类定义的属性OUTSIDE.我尝试了一些东西,但似乎无法在类中创建一个静态属性,我可以从构造函数更新.

我还要提一下,我需要能够在浏览器(Chrome)中执行此操作而不使用Babel或类似功能.

以下是我尝试过的一些事情的例子:

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 
Run Code Online (Sandbox Code Playgroud)

而另一个

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 "="
Run Code Online (Sandbox Code Playgroud)

Est*_*ask 18

static all = []ES6中没有这样的东西.类实例静态字段目前是阶段3提议,可以通过转换器使用,例如Babel.TypeScript中已经存在的实现可能以某种方式与这些提议不兼容,但 static all = []TSES.Next中有效.

Geo.all = [];
Run Code Online (Sandbox Code Playgroud)

在ES6中执行此操作是有效且可取的方法.替代方案是getter/setter对 - 或者只有getter属性的getter:

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

    return this._all;
  }

  constructor() { ... }
}
Run Code Online (Sandbox Code Playgroud)

静态属性中的跟踪实例通常不能被认为是一种好的模式,并且会导致无法控制的内存消耗和泄漏(正如评论中提到的那样).

  • 截至2017年12月,它现在是第3阶段提案:https://github.com/tc39/proposal-class-fields#field-declarations (4认同)