我正在尝试找出其他方法来设置 ES6 类的静态(或类)属性,然后在创建该类的新实例后更改它。
例如,假设我有一个名为 Geo
的类,我需要一个名为 all
的静态属性,它将为我提供 的所有实例的数组>地理
类。
这个版本有效:
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
不过,我宁愿不在类定义之外设置属性。我已经尝试了一些东西,但似乎无法在我可以从构造函数更新的类中创建静态属性。
我还应该提到我需要能够在不使用 Babel 或类似工具的情况下在浏览器 (Chrome) 中执行此操作。
以下是我尝试过的一些示例:
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 "="
最佳答案
没有static all = []
这样的东西在 ES6 中。类 instance和 static字段目前是第 3 阶段的提案,可以通过转译器使用,例如通天塔。现有的 TypeScript 实现可能在某种程度上与这些提议不兼容,但 static all = []
在 TS 和 ES.Next 中有效。
Geo.all = [];
是在 ES6 中执行此操作的有效且更可取的方法。替代方案是 getter/setter 对 - 或者只读属性的 getter:
class Geo {
static get all() {
if (!this._all)
this._all = [];
return this._all;
}
constructor() { ... }
}
跟踪静态属性中的实例通常不能被认为是一个好的模式,并且会导致无法控制的内存消耗和泄漏(正如评论中提到的那样)。
关于javascript - ES6 类 - 更新静态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44091167/