我正在尝试使用最合适的 ES6 语法定义一个带有已定义构造函数的 Javascript 类。起初,这样定义它很容易。
let param1 = 10;
let param2 = 'foo';
let param3 = 200;
let param4 = 'bar';
let props = {id: param1, options: { op1: param2, op2: param3, op3: param4 }};
console.log('Object props');
console.log(props);
class Test {
constructor(props){
this.id = props.id;
this.options = props.options;
}
}
let test1 = new Test(props);
console.log('Class test1');
console.log(test1.id);
console.log(test1.options.op2);
但是当我尝试使用解构来定义默认值时,对于构造函数的参数之一(op2
,嵌套对象 options
的一个属性),我我无法让它工作,而对于对象的 id
属性,我可以:
let param1 = 10;
let param2 = 'foo';
let param3 = 200;
let param4 = 'bar';
let props = {options: { op1: param2, op3: param4 }};
console.log('Object props');
console.log(props);
class Test {
constructor({id = 'defaultId', options = { op2:'0'}} = {}){
this.id = id;
this.options = options;
}
}
let test = new Test(props);
console.log('Class test');
console.log(test.id);
console.log(test.options);
console.log(test.options.op2);
我应该期望的是,当使用 console.log(test.options.op2)
进行调试时,会打印构造函数中设置的默认值,但我得到的是 undefined
.
另外我想知道在定义javascript类来初始化类参数时是否有更合适的ES6语法。
最佳答案
But when I try to use destructuring to define default values
constructor({id = 'defaultId', options = { op2:'0'}} = {}){
for one of the params of the constructor (op2, a property of the nested object options), I am not able to make it work, while for the id property of the object I am able.
默认值仅适用于单个参数/属性级别。如果没有参数或 undefined
被传递,{}
将用于第一个参数。如果对象没有 id
属性,将使用 'defaultId'
。如果对象没有 options
属性,将使用 {op2:'0'}
。如果您确实传递了一个带有 options
属性的对象,默认值将被忽略。
所以如果在对象中没有找到这样的属性,如果你想要对象的 op2
属性的默认值,你需要在 options
对象上使用解构本身:
constructor({id = 'defaultId', options: {op1, op2 = '0', op3} = {}} = {}) {
this.id = id;
this.options = {op1, op2, op3};
}
关于javascript - ES6 构造函数对象参数默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40655259/