我试图将参数传递给新的类构造函数,并在没有传递参数的情况下计算默认参数,同时仍可以选择通过其参数名称传递任何参数。
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
or b
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句