2017-05-20 56 views
6

我想弄清楚设置静态(或类)属性ES6类的替代方法,然后在类的新实例创建后更改它。例如 - 假设我有一个名为Geo的类,我需要一个名为'all'的静态属性,它会给我所有Geo类实例的数组。ES6类 - 更新静态属性

这个版本的作品:

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 

我宁愿没有设置类定义的酒店门外,虽然。我已经尝试了一些东西,但似乎无法在类中创建静态属性,我可以从构造函数中进行更新。

我还应该提到我需要能够在浏览器(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 

而另一

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 "=" 

任何帮助将不胜感激。

+1

在ES6中没有其他方法可以做到这一点。 – Bergi

+2

Geo.all = []'有什么问题? – dfsq

+3

你不应该有一个全局的实例集合 - 这将导致内存泄漏和模块化(例如可测试性)问题 – Bergi

回答

6

在ES6中没有这样的东西,如static all = []Class fields are stage 2 proposal,其可以通过转译器使用,例如,巴贝尔。

Geo.all = []; 

是在ES6中执行此操作的有效方法。另一种方法是吸气/设定部对 - 或只为只读属性的吸气剂:在静态属性

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

    return this._all; 
    } 

    constructor() { ... } 
} 

跟踪实例一般不能被认为是一种良好的图案,并且将导致不可控的内存消耗和泄漏(如它在评论中被提及)。

+3

截至2017年12月,现在是第3阶段的建议:https://github.com/tc39/proposal-class-fields#field-declarations –