繁体   English   中英

ES6相当于以下模式?

[英]ES6 equivalent of the following pattern?

我想在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);

这个的最佳替代方案是什么?

编辑

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

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

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

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模块的命名导出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM