Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for options object in class constructor

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();
like image 682
Mr.Smithyyy Avatar asked Dec 08 '22 15:12

Mr.Smithyyy


1 Answers

You actually just need a oneliner:

const defaultUser = {
  name: "Joe",
  age: 47
};

module.exports = class User {
  constructor(options) {
     Object.assign(this, defaultUser,  options)
  }
}
like image 113
Jonas Wilms Avatar answered Dec 28 '22 06:12

Jonas Wilms