JSON.stringify没有序列化可枚举属性?

时间:2015-03-05 09:35:53

标签: javascript

请参阅此脚本:https://jsfiddle.net/t5w060bv/

var A = function() {
  this.test1 = '1';
};
Object.defineProperty(A.prototype, 'test2', { value: '2', enumerable: true });
document.body.innerText = JSON.stringify(new A());

即使属性被定义为可枚举,它也不是序列化的。处理这种情况的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

原因是JSON.stringify只序列化它自己的属性而不是原型属性。

测试它

  

a.hasOwnProperty(#39&; TEST2&#39); //将返回false

     

a.hasOwnProperty(#39&; TEST1&#39); //将返回true

所以无论返回什么,都会被序列化。