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?
You can just have your constructor take one "config" parameter, and then say Object.assign(this, config). To have defaults, you can just set up a default object, or assign them outside the constructor as class properties.
EDIT To T.J. Crowder's point, technically anything passed in while using Object.assign() will be added to your object, which could be harmful in a number of ways. I have added a way to strip the config object to only contain a set of properties that you define. T.J.'s solution for this will work as well, I just did it differently so you have options.
function stripObjToModel(model, obj) {
// this method will modify obj
Object.keys(obj).forEach(function (key) {
if (!model.hasOwnProperty(key)) {
delete obj[key];
}
});
return obj;
}
class Person {
constructor(config = {}) {
var defaults = {
name: "Johnny Cash",
origin: "American",
profession: "singer"
};
Object.assign(this, defaults, stripObjToModel(defaults, config));
}
toString() {
return `${this.name} is an ${this.origin} ${this.profession}`;
}
}
const person = new Person();
console.log(person.toString());
// Returns 'Johnny Cash is an American singer'
const nina = new Person({
name : "Nina Simone",
foo: "bar",
toString: function () {return "Hello World!";}
})
console.log(nina.toString());
// Returns 'Nina Simone is an American singer'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With