简体   繁体   中英

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 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();

Make sure you have a default for the object itself.

module.exports = class User {
    constructor(options) {
        options = options || {}
        this.name = options.name || "Joe";
        this.age = options.age || 47;
    }
}

You could either set a default value for options, ie {} .

class User {
    constructor(options = {}) {
        this.name = options.name || "Joe";
        this.age = options.age || 47;
    }
}

or first check for options to be truthy and then access the value.

class User {
    constructor(options) {
        this.name = options && options.name || "Joe";
        this.age = options && options.age || 47;
    }
}

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 want to change to a configuration pattern, you can still keep your default parameter syntax:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM