I initialized my reuse classes like this (the 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 JSON.stringify does not give the expected result:
JSON.stringify(obj);
{}
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"]}
It also works great if 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"]}
What's happening?
Example here:
http://jsfiddle.net/FdzB6/
source
share