Xotic750 Xotic750 - 2 months ago 9
Javascript Question

Class constructor/function syntax with curly braces around parameter list

I've recently seen this code:



class Foo {
constructor({
a,
b,
c = []
}) {
this.a = a;
this.b = b;
this.c = c;
console.log(this);
}
}
const foo = new Foo({
a: 1,
b: 2
});





But I've never seen parameters defined with curly braces wrapping the parameter names. My linter complains about it, but the code works fine and so I assume that it is valid as it executes without error.

I've read the MDN docs about, class, constructor and default arguments. However, I do not see this pattern described anywhere (maybe I missed it?).

What is it I'm looking for, does this pattern have a name, or is it described somewhere?

Answer

It is parameter destructuring.

However, in this case, you could simply do

class Foo {
  constructor(opts) {
    Object.assign(this, {c: []}, opts);
    console.log(this);
  }
}

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

You should find some kind of "es6" flag for your linter to make it happy.