I've created a class and I would like to set some default options for values in case the user does not supply any arguments. I recently went from a constructor that took multiple parameters to an object because I believe it helps readability when the user is creating a new instance of the class.
Here is how I was doing it before:
module.exports = class User {
constructor(name = "Joe", age = 47) {
this.name = name;
this.age = age;
}
}
const User = require("./user");
const user = new User(); // Defaults to "Joe" and 47
In reality, my class has more parameters than that and the readability when using it becomes tough. So to solve this I switched to an options object that works much better but I can't seem to put default values. When I try to use this.name
it says this.name = options.name || "Joe" Cannot read property 'name' of undefined
even though I thought I set the default to "Joe"
Here is how I'm doing it now:
module.exports = class User {
constructor(options) {
this.name = options.name || "Joe";
this.age = options.age || 47;
}
}
const User = require("./user");
const user = new User();
You actually just need a oneliner:
const defaultUser = {
name: "Joe",
age: 47
};
module.exports = class User {
constructor(options) {
Object.assign(this, defaultUser, options)
}
}
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