我正在尝试将参数传递给新的类构造函数,并且如果没有传递任何参数,则要计算默认参数,同时仍然可以选择通过其参数名称传递任何参数。
class thing{
constructor({a = 0, b = 0}) {
if(a == 0){this.a= func();}
else {this.a = a;}
if(b == 0){this.b= func();
else {this.b = b;}
}
var defaultThing = new thing(); // returns Cannot destructure property `a` of 'undefined' or 'null'.
var parametersThing = new thing({b:20}); // returns {a = 0, b = 20}
问题是,如果没有传递任何参数,则会返回错误Cannot destructure property `a` of 'undefined' or 'null'.
。
如何使用默认参数,并且仍然能够不使用任何参数而不会遇到此错误?
在构造函数签名中,当属性不存在于接收到的参数上但没有默认参数时,您提供了解构默认值。为此,您添加一个默认参数:
constructor({a = 0, b = 0} = {}) {
// ...
如果不带任何参数调用它,则默认({}
)参数值将插入,然后解构默认值将插入,因为{}
对象没有a
或b
。