javascript - ES6 类实例化中的错误消息
问题描述
在使用 JavaScript 多年之后,我即将编写我的第一个 JS 类(!)。如果未提供必需的构造函数参数,我想做的是抛出错误。有点像这样
class Foo {
constructor(options) {
super(options);
if (!(this.reqd = options.reqd)) {
return 'error: 'reqd' is required'
}
this.optional = options.optional;
}
}
const f = new Foo({optional: 'frob'})
会抛出错误,但const f = new Foo({reqd: 'blub'})
或const f = new Foo({reqd: 'blub', optional: 'frob'})
会工作。
这可以做到吗?
解决方案
检查options
对象是否具有带有 的reqd
属性hasOwnProperty
,如果没有,则抛出错误:
class Foo {
constructor(options) {
// super(options);
if (!options.hasOwnProperty('reqd')) {
throw new Error('reqd property is required');
}
this.reqd = options.reqd;
// if you don't want to assign `undefined` for a non-existent optional property,
// use a hasOwnProperty check before assigning
this.optional = options.optional;
}
}
const f1 = new Foo({ reqd: 'val' });
console.log('next');
const f2 = new Foo({ optional: 'val' });
如果你想抛出一个错误,你必须明确throw
它,否则不会有错误(或者,至少直到以后不会)。只返回一个字符串并没有错误。
推荐阅读
- amazon-dynamodb - AWS GET api 查询 DynamoDB,在映射模板中使用二级索引
- c# - 自定义记录器类的性能分析,用于读取 Word 文档的应用程序
- azure - az aks install-connector 因“--name 未知参数”而失败
- windows - LNK1181 链接器错误,无法打开输入文件,在 Windows 10 上 -- 虚假,然后解决
- generics - 如何对包含不同类型的链表进行静态调度,这些类型都实现了一个特征?
- c# - Windows 窗体应用程序 C# - 更改数组
- google-app-engine - AppEngine Flex 自定义就绪和活跃度端点未触发
- jquery - 如何以动画的形式显示随机的 html 类标签?
- python - 在 Python 字典中查找元素
- woocommerce - 在 woocomerce 变量订阅产品中为自定义产品属性添加描述字段