Javascript JSON.stringify doesn't handle prototype correctly?
javascript, json, prototype
Solution
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. 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).
Problem
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(obj); ``` {} 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"]} 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"]} What's going on? Example here: http://jsfiddle.net/FdzB6/