1

我想像这样在 ES6 类中使用静态类属性(stage-0) -

class Button {
  static size = {
    SMALL: "SMALL",
    BIG: "BIG"
  }
}

class UILibrary {
  consturctor() {
    this.button = new Button();
  }
}

// I can't access static properties of a class instance :(
const LibraryA = new UILibrary();
console.log(LibraryA.button.size.SMALL);

什么是最好的选择?

编辑

这个问题不是关于在 ES6/7 中创建类属性(阶段 0 已经支持),也不是关于创建静态方法。我只是想找到一种允许将类似枚举的对象附加到类实例的模式。因此,没有一个重复的问题建议是有效的。

4

1 回答 1

3

我无法访问类实例的静态属性:(

是的,如果它们是静态属性,那么您需要在构造函数上访问它们:

console.log(Button.size.SMALL);
console.log(LibraryA.button.constructor.size.SMALL);

(有关差异的讨论,请参见此处)

我只是想找到一种允许将类似枚举的对象附加到类实例的模式。

如果您希望它们在实例上可用,请不要让它们static

class Button {
  // without the experimental syntax, do the assignment in the constructor
  size = {
    SMALL: "SMALL",
    BIG: "BIG"
  }
}

或者,不要删除static关键字,而是将它们放在原型上,这样就不会一遍又一遍地重新创建对象:

class Button {}
Button.prototype.size = {
  SMALL: "SMALL",
  BIG: "BIG"
};

或者,也许您根本不应该将它们枚举放在类中,而只使用 ES6 模块的命名导出。

于 2016-08-24T05:50:18.360 回答