Default value for options object in class constructor

后端 未结 4 1057
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  旧时难觅i
    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
    

提交回复
热议问题