目前在ES5中,我们很多人在框架中使用以下模式来创建类和类变量,这很舒服:
// ES 5
FrameWork.Class({
variable: 'string',
variable2: true,
init: function(){
},
addItem: function(){
}
});
在ES6中,你可以在本地创建类,但是没有选项可以有类变量:
// ES6
class MyClass {
const MY_CONST = 'string'; // <-- this is not possible in ES6
constructor(){
this.MY_CONST;
}
}
遗憾的是,上述方法不起作用,因为类只能包含方法。
我知道我能做到。myVar = true在构造函数…但我不想'垃圾'我的构造函数,特别是当我有20-30+参数为一个更大的类。
我想了很多方法来处理这个问题,但还没有找到一个好的。(例如:创建一个ClassConfig处理程序,并传递一个参数对象,该对象与类分开声明。然后处理程序将附加到类。我也在考虑以某种方式集成WeakMaps。)
你会有什么样的想法来处理这种情况?
我解决这个问题的方法,这是另一个选择(如果你有jQuery可用),是在一个老式的对象中定义字段,然后用该对象扩展类。我也不想在构造函数中添加赋值,这似乎是一个整洁的解决方案。
function MyClassFields(){
this.createdAt = new Date();
}
MyClassFields.prototype = {
id : '',
type : '',
title : '',
createdAt : null,
};
class MyClass {
constructor() {
$.extend(this,new MyClassFields());
}
};
——根据Bergi的评论更新。
没有JQuery版本:
class SavedSearch {
constructor() {
Object.assign(this,{
id : '',
type : '',
title : '',
createdAt: new Date(),
});
}
}
你仍然会得到“胖”构造函数,但至少它都在一个类中,并在一次命中赋值。
编辑# 2:
我现在已经走了一圈,现在在构造函数中赋值,例如。
class SavedSearch {
constructor() {
this.id = '';
this.type = '';
this.title = '';
this.createdAt = new Date();
}
}
为什么?真的很简单,使用上面的加上一些JSdoc注释,PHPStorm就能够在属性上执行代码补全。在一次命中分配所有的变量是很好的,但无法编码完成属性,在我看来,不值得(几乎肯定是微乎其微的)性能收益。