Default value for options object in class constructor

后端 未结 4 1049
爱一瞬间的悲伤
爱一瞬间的悲伤 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
    慢半拍i (楼主)
    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;
        }
    }
    

提交回复
热议问题