Question

I am using the JQuery json plugin and trying to convert a custom object to JSON using the toJSON function. Here is the object:

function Customer(firstName, lastName, age) {

    Customer.prototype.firstName = firstName;
    Customer.prototype.lastName = lastName;
    Customer.prototype.age = age; 
}

And here is the $.toJSON applied:

  var customer = new Customer('mohammad', 'azam', 28);

        var a = $.toJSON(customer); 

For some reason "a" is always empty.

But if I use the following code:

var params = new Object(); params.firstName = 'Mohammad'; params.lastName = 'Azam'; params.age = 28;

var a = $.toJSON(params);

then it works fine!

What am I missing when trying to perform toJSON on a custom object.

Was it helpful?

Solution

I've not had time to test this (so forgive me if this is incorrect), but I believe that by assigning:

 Customer.prototype.firstName = firstName;

you are doing the equivalent of setting the static firstName property for the whole class.

Have you tried:

this.firstName = firstName;

That is the way it is normally done in Object Oriented JS anyway.

In short, the function would then be:

function Customer(firstName, lastName, age) {

    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top