如何在类构造函数中加入限制?

时间:2018-01-24 08:59:42

标签: javascript ecmascript-6

Interpolation类的构造函数有两个数组。如何设置限制,以便在创建对象期间,这两个数组的长度必须相等。

class Interpolation {
    constructor (x, fx) {
        if ( x instanceof Array && fx instanceof Array ) {
            if ( x.length === fx.length ) {
                this.input = x;
                this.output = fx;
            } else { throw 'Unmatching array' }
        } else throw 'Please pass in array';
    }
}

我试过这个,在对象创建过程中,源代码也像这样打印在控制台上

C:\NeuralNetwork\interpolation.js:7
                        } else { throw('Invalid Array') }
                                 ^
Invalid Array

1 个答案:

答案 0 :(得分:1)

像这样:

class Interpolation {
    constructor (x, fx) {
        if(!(x instanceof Array)) {
            throw('parameter `x` must be an Array.');
        }

        if(!(fx instanceof Array)) {
            throw('parameter `fx` must be an Array,');
        }

        if(x.length !== fx.length) {
            throw('the length of these two arrays(x, fx) must be equal');
        }

        this.input = x;
        this.output = fx;
    }
}