Search code examples
javascriptconstructorecmascript-6defaultdestructuring

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."


Solution

  • 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}'`);
    }