Convert ES6 Class with Symbols to JSON

后端 未结 5 1872
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 23:31

I have hardcoded classes to represent models in my Aurelia application. Here\'s a model \'PostEdit\':

var _postID = Symbol();
var _title = Symbol();
var _te         


        
5条回答
  •  醉酒成梦
    2020-12-08 23:58

    Symbol-based private variables are considerable recipe for encapsulation in ES6. The encapsulation in JS is rarely justified, but these are accessors (not symbols) that cause problems here.

    Accessors are prototype methods in ES6 classes. So the property is defined not on instance but on prototype, it is non-enumerable. It can be seen in transpiled code, or by checking

    postEditInstance.hasOwnProperty('postID') === false
    Object.getPrototypeOf(postEditInstance).hasOwnProperty('postID') === true
    Object.getPrototypeOf(postEditInstance).propertyIsEnumerable('postID') === false
    

    JSON.stringify, on the other hand, serializes only own enumerable properties of the object.

    The solution is to use toJSON method to serialize the object according to the desirable conditions. Or to use Occam's razor on model's accessors, especially if they aren't crucial there.

提交回复
热议问题