【发布时间】:2018-08-20 06:35:17
【问题描述】:
我正在为我的 Express Web 应用程序定义一个 ECMAScript 6 类。它有一个强制属性和一些可选属性。必填字段需要在类构建期间分配,而可选字段则不需要。
可选属性只需要按需设置。
class Item{
constructor(mandatoryField) {
this._mandatoryField = mandatoryField;
this._optionalField1 = undefined;
this._optionalField2 = undefined;
this._optionalField3 = undefined;
}
get mandatoryField() {
return this._mandatoryField;
}
set mandatoryField(newVal){
if(newVal){
this._mandatoryField = newVal;
}
}
get optionalField1() {
return this._optionalField1;
}
set optionalField1(newVal){
if(newVal){
this._optionalField1 = newVal;
}
}
get optionalField2() {
return this._optionalField2;
}
set optionalField2(newVal){
if(newVal){
this._optionalField2 = newVal;
}
}
get optionalField3() {
return this._optionalField3;
}
set optionalField3(newVal){
if(newVal){
this._optionalField3 = newVal;
}
}
}
var item1 = new Item("mandVal");
item1.mandatoryField; // access the mandatory property
item1.optionalField1("optVal"); // set the optional property
item1.optionalField1; // access the optional property
上面的声明有问题吗?如何使可选属性在类声明中具有默认值?
【问题讨论】:
-
而不是 assining undefined ,分配默认值
-
您需要分配哪个默认值?
-
你需要这些setter和getter做什么?它们似乎完全是多余的,并且忽略了虚假值的分配。
-
@Bergi。构造对象后,需要 setter 和 getter 来分配和访问属性。
-
类初始化时可选属性未知。他们将在以后分配。
标签: javascript node.js express ecmascript-6