Default value for options object in class constructor

后端 未结 4 1032
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 05:35

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 mu

相关标签:
4条回答
  • 2021-01-14 05:50

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-14 05:52

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

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-14 05:52

    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
    
    0 讨论(0)
  • 2021-01-14 05:54

    You actually just need a oneliner:

    const defaultUser = {
      name: "Joe",
      age: 47
    };
    
    module.exports = class User {
      constructor(options) {
         Object.assign(this, defaultUser,  options)
      }
    }
    
    0 讨论(0)
提交回复
热议问题