JSON.stringify() works on literal objects, such as:
var myObjectLiteral = {
a : "1a",
b : "1b",
c : 100,
d : {
da : "1da",
dc : 200
}
};
var myObjectLiteralSerialized = JSON.stringify(myObjectLiteral);
myObjectLiteralSerialized is assigned, "{"a":"1a","b":"1b","c":100,"d":{"da":"1da","dc":200}}" as expected.
But, if I define the class with a ctor like this,
function MyClass() {
var a = "1a";
var b = "1b";
var c = 100;
var d = {
da : "1da",
dc : 200
};
};
var myObject = new MyClass;
var myObjectSerialized = JSON.stringify(myObject);
then myObjectSerialized is set to the empty string, "".
I think the reason is because the class version ends up being the prototype of the instantiated class which makes it's properties "owned" by the prototype and JSON will only stringify props owned by the instance object, myObject.
Is there a simple way to get my classes into JSON strings w/o writing a bunch of custom code?