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

前端 未结 5 902
花落未央
花落未央 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:45

    Yes, it is by design.

    As defined in ECMA, only own enumerable properties are serialized (stringify() is defined in terms of Object.keys(), among others).

    Property accessors are defined on prototypes, both in TypeScript and ES6.

    And answering your last question, that is the most eficient way to perform this operation.

    Beside that, only a) defining an toJSON() to each object part of the serialization, or b) passing a replacer function/array as 2nd argument to JSON.stringify().

    Whitelist properties from prototype:

    JSON.stringify(instance, Object.keys(instance.constructor.prototype))
    

提交回复
热议问题