Object.defineProperty on a prototype prevents JSON.stringify from serializing it

前端 未结 5 903
花落未央
花落未央 2020-12-05 11:05

I\'m using TypeScript to define some classes and when I create a property, it generates the equivalent to Class1 in the following plunkr:

http://plnkr.c

5条回答
  •  孤城傲影
    2020-12-05 11:28

    As you've discovered, it won't serialize properties defined on prototype.

    I know it's not ideal, but another option is to do this:

    class Class1 {
        private _name = "test1";
    
        Name: string; // do this to make the compiler happy
    
        constructor() {
            Object.defineProperty(this, "Name", {
                get: function() { return this._name; },
                set: function(value) { this._name = value; },
                enumerable: true
            });
        }
    }
    

    Defining the property on the instance will serialize the property.

提交回复
热议问题