我创建了一个JS类。以下是代码:
export default class Service {
constructor(
serviceId,
serviceName,
serviceDescription,
serviceImageName,
categoryId,
servicePrice,
currencyCode,
acceptPayment,
serviceDuration,
multipleBookingPerSlot,
mode,
tzSupport,
minOptionCount
) {
try{
this.id = serviceId;
this.title = serviceName;
this.subTitle = serviceDescription;
this.imageUrl = serviceImageName;
this.categoryId = categoryId;
this.price = servicePrice;
this.currencyCode = currencyCode;
this.acceptPayment = acceptPayment;
this.meetingDuration = serviceDuration;
this.multipleBookingPerSlot = multipleBookingPerSlot;
this.serviceName = serviceName;
this.mode = mode;
this.tzSupport = tzSupport;
this.session = minOptionCount
} catch(e){
if(e instanceof ReferenceError){
console.error("Service data missing.")
}
}
}
}
我的目标是每当Service
的新对象创建类似new Service('1')
时,如果任何密钥丢失,代码应该抛出错误并停止执行。我怎样才能做到这一点?
答案 0 :(得分:2)
如果来电者没有提供足够的参数,您将无法获得ReferenceError
,您只需在参数中看到undefined
。
你有13个参数(远远太多)。你可以做蛮力的事情:
if (arguments.length < 13) {
throw new Error("Missing arguments");
}
相反,我建议使用构建器模式或选项对象而不是13个离散参数。超过三个参数相当难以管理。
例如,使用选项对象:
export default class Service {
constructor(
options
) {
["id", "title", "subTitle", "imageUrl", "categoryId", "price", "currencyCode",
"acceptPayment", "meetingDuration", "multipleBookingPerSlot", "serviceName",
"mode", "tzSupport", "session"].forEach(name => {
if (!options.hasOwnProperty(name)) {
throw new Error(name + " is a required option");
}
});
Object.assign(this, options);
}
}
用法:
let s = new Service({id: 1, title: "foo", /*...etc...*/});
这样,来电者就不会在参数范围内迷失。
然而,如果验证参数值是否重要,那么验证其值是否也很重要?没有什么可以阻止我用13个完全无效的参数调用new Service
(例如undefined
重复13次)。
所以我可能会使用一个options对象(因为它对调用者来说更容易)与参数解构相结合,然后进行单独验证,例如:
export default class Service {
constructor({ // <== Notice the {
id,
name,
decription,
imageUrl,
categoryId,
price,
currencyCode,
acceptPayment,
meetingDuration,
multipleBookingPerSlot,
mode,
tzSupport,
minOptionCount
}) { // <== And the }
this.id = validate.positiveNumber(id);
this.title = validate.nonBlank(name);
this.subTitle = validate.nonBlank(description);
this.imageUrl = validate.URL(imageUrl);
this.categoryId = validate.positiveNumber(categoryId);
this.price = validate.price(price);
this.currencyCode = validate.currencyCode(currencyCode);
this.acceptPayment = validate.boolean(acceptPayment);
this.meetingDuration = validate.duration(meetingDuration);
this.multipleBookingPerSlot = validate.boolean(multipleBookingPerSlot);
this.serviceName = this.title; // Already validated
this.mode = validate.mode(mode);
this.tzSupport = validate.tzSupport(tzSupport);
this.session = validate.whateverThisIs(minOptionCount);
}
}
...其中validate
是一组可重复使用的验证。用法与上述相同:
let s = new Service({id: 1, title: "foo", /*...etc...*/});
答案 1 :(得分:0)
正如我已经评论过,将undefined赋值给对象属性是完全有效的。解决方案可能是检查Arraylike与undefined的参数值:
constructor(a,b,c){
if(arguments.length!=3){//check length
return;
}
for(var a=0;a<arguments.length;a++){
if(arguments[a]===undefined){//check against undefined
return;
}
}
//your code
}