我想在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);
最好的选择是什么?
编辑:
这个问题不是关于在Stage-0已经支持的ES6 / 7中创建类属性,也不是关于创建静态方法。我只是在寻找一种允许将枚举类对象附加到类实例的模式。因此,所有重复的问题建议均无效。
最佳答案
我无法访问类实例的静态属性:(
是的,如果它们是静态属性,那么您需要在构造函数上访问它们:
console.log(Button.size.SMALL);
console.log(LibraryA.button.constructor.size.SMALL);
(有关差异的讨论,请参见here)
我只是在寻找一种允许将枚举类对象附加到类实例的模式。
如果您希望它们在实例上可用,请不要将它们设为
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模块的命名出口即可。