ES6类 - 更新静态属性 [英] ES6 Classes - Updating Static Properties
问题描述
我试图找出将静态(或类)属性设置为ES6类的替代方法,然后在创建类的新实例后更改它。
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.
例如,假设我有一个名为 Geo
的类,我需要一个名为<$ c的静态属性$ c>所有,它将为我提供 Geo
类的所有实例的数组。
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.
此版本有效:
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
我宁愿不设置类定义的属性OUTSIDE。我尝试了一些东西,但似乎无法在类中创建一个静态属性,我可以从构造函数更新。
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.
我还应该提一下,我需要能够在浏览器(Chrome)中执行此操作而不使用Babel或类似功能。
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
另一个
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 "="
推荐答案
没有这样的事情< ES6 中的code> static all = [] 。 实例和 static 字段是目前阶段3的提案,可以通过转换器使用,例如巴贝尔。 TypeScript中已经存在可能以某种方式与这些提案不兼容的实现,但 static all = []
在 TS 和 ES.Next 。
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 = [];
是在ES6中执行此操作的有效和可取的方法。替代方案是getter / setter对 - 或者只有get-only属性的getter:
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).
这篇关于ES6类 - 更新静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!