简体   繁体   English

JavaScript JSON.stringify无法正确处理原型吗?

[英]Javascript JSON.stringify doesn't handle prototype correctly?

I've been initializing my reusable classes like this (constructor is usually a copy-constructor): 我一直在像这样初始化我的可重用类(构造函数通常是一个复制构造函数):

function Foo() {}
Foo.prototype.a = "1";
Foo.prototype.b = "2";
Foo.prototype.c = [];
var obj = new Foo();
obj.c.push("3");

but the JSON.stringify does not produce the expected result: 但JSON.stringify不会产生预期的结果:

JSON.stringify(obj);

{} {}

The variables work as expected for everything else. 变量对其他所有功能均起作用。
If toJSON is overridden, it works fine: 如果toJSON被覆盖,则可以正常工作:

Foo.prototype.toJSON = function () {
    return {
        a: this.a,
        b: this.b,
        c: this.c
    };
};
JSON.stringify(obj);

{"a":"1","b":"2","c":["3"]} {“ a”:“ 1”,“ b”:“ 2”,“ c”:[“ 3”]}

It also works fine if the variables are defined inside the constructor: 如果在构造函数中定义了变量,它也可以正常工作:

function Alt() {
    this.a = 1;
    this.b = "2";
    this.c = [];
}
JSON.stringify(obj);

{"a":1,"b":"2","c":["3"]} {“ a”:1,“ b”:“ 2”,“ c”:[“ 3”]}

What's going on? 这是怎么回事?

Example here: http://jsfiddle.net/FdzB6/ 此处的示例: http : //jsfiddle.net/FdzB6/

Properties on an object's prototype (that is, the prototype of its constructor) are readable via a reference to an the object: 通过引用对象可以读取对象原型(即其构造函数的原型)上的属性:

function Constructor() { }
Constructor.prototype.a = "hello world";

var x = new Constructor();
alert(x.a); // "hello world"

However, those properties really are "stuck" on the prototype object: 但是,这些属性确实“卡在”原型对象上:

alert(x.hasOwnProperty("a")); // false

The JSON serializer only pays attention to properties that directly appear on objects being processed. JSON序列化程序仅关注直接出现在正在处理的对象上的属性。 That's kind-of painful, but it makes a little sense if you think about the reverse process: you certainly don't want JSON.parse() to put properties back onto a prototype (which would be pretty tricky anyway). 这有点痛苦,但是如果您考虑反向过程,这有点道理:您当然不希望JSON.parse()将属性放回到原型上(无论如何还是很棘手的)。

your answer lies Why is JSON.stringify not serializing prototype values? 您的答案在于, 为什么JSON.stringify不序列化原型值?

JSON.stringify only does "own" properties. JSON.stringify仅具有“自有”属性。

In your first example: prototype members are being set, and then calling Stringify on the object itself, which does not have its own properties. 在第一个示例中:设置原型成员,然后对不具有自己属性的对象本身调用Stringify

In your second: this.a will climb the chain until it finds the property 在您的第二个中: this.a将爬链直到找到该物业

In the third: You are setting properties directly on the object and not its prototype 第三:直接在对象上设置属性,而不是在其原型上设置属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM