JSON stringify ES6 class property with getter/setter

后端 未结 5 1801
一向
一向 2020-11-30 13:40

I have a JavaScript ES6 class that has a property set with set and accessed with get functions. It is also a constructor parameter so the class can

5条回答
  •  爱一瞬间的悲伤
    2020-11-30 14:16

    If you want to avoid calling toJson, there is another solution using enumerable and writable:

    class MyClass {
    
      constructor(property) {
    
        Object.defineProperties(this, {
            _property: {writable: true, enumerable: false},
            property: {
                get: function () { return this._property; },
                set: function (property) { this._property = property; },
                enumerable: true
            }
        });
    
        this.property = property;
      }
    
    }
    

提交回复
热议问题