在创建新对象时没有传递值时如何使用默认参数?
How can I use default parameters when no value are passed in creating a new object?
我正在尝试将参数传递给新的 class 构造函数,如果没有传递参数,则计算默认参数,同时仍然可以选择通过参数名称传递任何参数。
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'.
。
如何使用默认参数并且仍然能够不使用参数而不会遇到此错误?
在您的构造函数签名中,您已经为接收到的参数上不存在属性但没有默认参数的情况提供了解构默认值。为此,您添加一个默认参数:
// vvvv−−− default parameter value
constructor({a = 0, b = 0} = {}) {
// ^^^−−−−^^^−−−−−−−−− destructuring defaults
// ...
如果你不带参数调用它,默认参数值 ({}
) 开始,然后解构默认值开始,因为 {}
对象没有 a
或 b
.
我正在尝试将参数传递给新的 class 构造函数,如果没有传递参数,则计算默认参数,同时仍然可以选择通过参数名称传递任何参数。
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'.
。
如何使用默认参数并且仍然能够不使用参数而不会遇到此错误?
在您的构造函数签名中,您已经为接收到的参数上不存在属性但没有默认参数的情况提供了解构默认值。为此,您添加一个默认参数:
// vvvv−−− default parameter value
constructor({a = 0, b = 0} = {}) {
// ^^^−−−−^^^−−−−−−−−− destructuring defaults
// ...
如果你不带参数调用它,默认参数值 ({}
) 开始,然后解构默认值开始,因为 {}
对象没有 a
或 b
.