javascript - ES6 类 - 更新静态属性

标签 javascript class oop object ecmascript-6

我正在尝试找出其他方法来设置 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 中。类 instancestatic字段目前是第 3 阶段的提案,可以通过转译器使用,例如通天塔。现有的 TypeScript 实现可能在某种程度上与这些提议不兼容,但 static all = []TSES.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/

相关文章:

javascript - 在选择合适的 iOS Mobile Safari Web 开发工具(jQuery Mobile/Sencha Touch/等)时感到沮丧

javascript - 如何在 javascript 的 Ant 构建脚本中使用 YUI Compressor

r - 检查多个数据帧的数据类型的函数 R

c# - 迭代器中的副作用被认为是有害的?

php - 派生类构造函数名称在 PHP 中被弃用了吗?

javascript - 如何在 console.log() 上显示的表中获取值?

javascript - 使用 Jquery 选择一个 td 元素

javascript - AngularJS 根据 GET 请求将新项目推送到数组

c++ - 应该如何构建基本的类层次结构?

java - 创建其他类的数组。