首页 > 解决方案 > 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'})会工作。

这可以做到吗?

标签: javascriptclassecmascript-6

解决方案


检查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它,否则不会有错误(或者,至少直到以后不会)。只返回一个字符串并没有错误。


推荐阅读