3

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?

2
  • 1
    Those are not properties, but local variables. Commented Sep 9, 2011 at 3:03
  • 1
    Also, function declarations don't have trailing semi-colons. Commented Sep 9, 2011 at 3:10

1 Answer 1

13

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.