Reputation: 141
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?
Upvotes: 3
Views: 11175
Reputation: 322502
Your MyClass
isn't setting any properties on the object being constructed. It's just creating local variables to the constructor.
To create properties, set properties on this
in the constructor, since this
references the new object:
function MyClass() {
this.a = "1a";
this.b = "1b";
this.c = 100;
this.d = {
da : "1da",
dc : 200
};
}
Also, you typically wouldn't add properties to the .prototype
object inside the constructor. They only need to be added once, and will be shared among objects created from the constructor.
function MyClass() {
this.a = "1a";
this.b = "1b";
this.c = 100;
this.d = {
da : "1da",
dc : 200
};
}
MyClass.prototype.toJSON = function() {
return; // ???
}
MyClass.prototype.equals = function(other) {
if(other != null && other.prototype == this) {
if(this.a == other.a
&& this.b == other.b
&& this.c == other.c
&& this.d.da == other.d.da
&& this.d.dc == other.d.dc)
return true;
}
return false;
}
Upvotes: 13