Setting javascript object properties from default values ​​for constructor using parameter destruction

This is a bit of a tricky question about destructuring ES6 using the default javascript object constructor.

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

so i did it

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 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 the corresponding line similar to this in the constructor body

this.newParameter=newParameter;

Is there an even more elegant way to add a destructed parameter with a default value that is automatically bound to "this".

+4
4

, ,

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

  console.log(`this.a::'${this.a}' this.b::'${this.b}'`);
}
+2

, new this.

, object .
literal .

function returnObject(a = 1, b = 2, c = 3) {
  return {
    a,
    b,
    c
  }
}

console.log(returnObject())
Hide result
0

, , Object.assign.

function bla(props={}) {
  Object.assign(this, {a:3,b:6}, props);
  console.log(`this.a::'${this.a}' this.b::'${this.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"
Hide result

, , , , .

0
source

If the goal is to use the variable names exactly once, then this is what I would do:

const foo = new Foo({ a: 1 });

console.log(`foo { a: ${foo.a}, b: ${foo.b} }`);

function Foo(config = {}) {
    const defaults = { a: 3, b: 6 };

    for (const [key, val] of Object.entries(defaults))
        ({ [key]: this[key] = val } = config);
}
Run codeHide result

Now you need to update the object defaults, and you're done.


Actually, create a constructor constructor by abstracting this template:

const Foo = defcons({ a: 3, b: 6 });

const foo = new Foo({ a: 1 });

console.log(`foo { a: ${foo.a}, b: ${foo.b} }`);

function defcons(defaults) {
    return function (config = {}) {
        for (const [key, val] of Object.entries(defaults))
            ({ [key]: this[key] = val } = config);
    };
}
Run codeHide result

Now you can easily create as many constructors as you want.

0
source

Source: https://habr.com/ru/post/1684035/


All Articles