Currently in ES5 many of us are using the following pattern in frameworks to create classes and class variables, which is comfy:
(当前在ES5中,我们许多人在框架中使用以下模式来创建类和类变量,这很方便:)
// ES 5
FrameWork.Class({
variable: 'string',
variable2: true,
init: function(){
},
addItem: function(){
}
});
In ES6 you can create classes natively, but there is no option to have class variables:
(在ES6中,您可以本地创建类,但是没有选择可以使用类变量:)
// ES6
class MyClass {
const MY_CONST = 'string'; // <-- this is not possible in ES6
constructor(){
this.MY_CONST;
}
}
Sadly, the above won't work, as classes only can contain methods.
(可悲的是,上述方法不起作用,因为类只能包含方法。)
I understand that I can this.myVar = true
in constructor
…but I don't want to 'junk' my constructor, especially when I have 20-30+ params for a bigger class.
(我知道我可以在constructor
this.myVar = true
…但是我不想“垃圾”我的构造函数,尤其是当我有20-30个以上的大型类参数时。)
I was thinking of many ways to handle this issue, but haven't yet found any good ones.
(我正在考虑解决该问题的多种方法,但尚未找到任何好的方法。)
(For example: create a ClassConfig
handler, and pass a parameter
object, which is declared separately from the class. Then the handler would attach to the class. I was thinking about WeakMaps
also to integrate, somehow.)((例如:创建一个ClassConfig
处理程序,并传递一个与类分开声明的parameter
对象。然后该处理程序将附加到该类上。我在考虑将WeakMaps
也以某种方式进行集成。))
What kind of ideas would you have to handle this situation?
(您将如何处理这种情况?)
ask by wintercounter translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…