Default value for options object in class constructor

后端 未结 4 1033
爱一瞬间的悲伤
爱一瞬间的悲伤 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:54

    You actually just need a oneliner:

    const defaultUser = {
      name: "Joe",
      age: 47
    };
    
    module.exports = class User {
      constructor(options) {
         Object.assign(this, defaultUser,  options)
      }
    }
    

提交回复
热议问题