Setting an ES6 class getter to enumerable

后端 未结 3 2053
猫巷女王i
猫巷女王i 2020-12-09 08:06

I have an ES6 class (transcompiled with babeljs) with a getter property. I understand that these properties are not enumerable by default. However, I do not understand why I

3条回答
  •  时光说笑
    2020-12-09 08:44

    You may do trick like this:

    class Person {
      static createFields({ name }) {
        return {
          name,
          get greeting() {
            return `Hello, I'm ${this.name}`;
          }
        }
      }
    
      constructor(...args) {
        const inst = this.constructor.createFields(...args)
        const desc = Object.getOwnPropertyDescriptors(inst)
        Object.defineProperties(this, desc)
        return this
      }
    }
    

    Benefit is that getters on plain object are enumerable and configurable by default, you don't have to care about these modifiers every time.

    But... it looks kinda weird) Not sure whether this should be really used.

提交回复
热议问题