When you're writing ES6 classes you can use destructuring in the constructor to make it easier to use default options:
class Person {
constructor({
name = "Johnny Cash",
origin = "American",
profession = "singer"
} = {}) {
this.name = name;
this.origin = origin;
this.profession = profession;
}
toString() {
return `${this.name} is an ${this.origin} ${this.profession}`;
}
}
This allows you do to things like this:
const person = new Person();
console.log(person.toString());
// Returns 'Johnny Cash is an American singer'
const nina = new Person({
name : "Nina Simone"
})
console.log(nina.toString());
// Returns 'Nina Simone is an American singer'
However, you need to repeat the arguments in the constructor to assign them to the class instance. I already found out you can do this to make it less verbose:
Object.assign(this, { name, origin, profession });
But you still need to repeat those three variables. Is there any way to make the assignment even shorter without repeating the variables?