【问题标题】:Enumerable properties are not serialized by JSON.stringify? [duplicate]JSON.stringify 不序列化可枚举属性? [复制]
【发布时间】:2015-03-05 09:35:52
【问题描述】:

查看此脚本: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());

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

【问题讨论】:

  • 见this question。基本上,JSON.stringify() 就是这样被 ES5 定义的。

标签: javascript


【解决方案1】:

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

测试一下

a.hasOwnProperty('test2'); // 将返回 false

a.hasOwnProperty('test1'); // 将返回 true

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 2014-01-20
    • 1970-01-01
    • 2020-11-19
    相关资源
    最近更新 更多