Default value for options object in class constructor

后端 未结 4 1031
爱一瞬间的悲伤
爱一瞬间的悲伤 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;
        }
    }
    

提交回复
热议问题