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");
,但是JSON.stringify无法产生预期的结果:
but the JSON.stringify does not produce the expected result:
JSON.stringify(obj);
{}
变量在其他所有方面均按预期工作.
如果toJSON被覆盖,则可以正常工作:
The variables work as expected for everything else.
If toJSON is overridden, it works fine:
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"]}
这是怎么回事?
此处的示例: 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
JSON序列化程序仅关注直接出现在正在处理的对象上的属性.这有点痛苦,但是如果您考虑反向过程,这有点道理:您当然不希望JSON.parse()
将属性放回到原型上(无论如何还是很棘手的).
The JSON serializer only pays attention to properties that directly appear on objects being processed. 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).
这篇关于JavaScript JSON.stringify无法正确处理原型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!