I am trying to define a Javascript class with a defined constructor with params with the most proper ES6 syntax. At first, it is easy to define it like this.
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);
But when I try to use destructuring to define default values, 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:
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);
What I should expect is that when debugging with console.log(test.options.op2)
prints the default value set in the constructor, but instead I am gettting undefined
.
Also I would like to know if is there any more proper ES6 syntax when defining javascript classes to initialize class params.