Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting javascript object properties from constructor default values using parameter destructuring

This is a bit of a tricky question regarding ES6 destructuring with default usage in a javascript object constructor.

I would like to receive a destructured parameters object with default values for my object constructor

so what i did was this

function bla({a=3,b=6}={}){
  this.a=a;
  this.b=b;
  console.log(`this.a::'${this.a}' this.b::'${this.b}' a::'${a}' b::'${b}'`);
}

let myObject= new bla({a:1});
console.log(`myObject.a::'${myObject.a}' myObject.b::'${myObject.b}'`); // only a got overriden with value "1" and b remained its defauly value "6"

I know that what i did works. However, you can see that this is a bit of a code smell, because every time i need to add a new parameter to the constructor (for example {newParameter=3}) i also need to go down and add a matching line like this in the constructor body

this.newParameter=newParameter;

Is there any more elegant way to add a destructured parameter with default value which automatically is attached to "this."

like image 991
tal shachar Avatar asked May 29 '26 11:05

tal shachar


1 Answers

I personally think your current approach is the most readable, but you can technically also do

function bla(obj = {}){
  ({
    a: this.a = 3,
    b: this.b = 6,
  } = obj);

  console.log(`this.a::'${this.a}' this.b::'${this.b}'`);
}
like image 79
loganfsmyth Avatar answered Jun 01 '26 04:06

loganfsmyth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!