tags:

views:

91

answers:

1

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.

+2  A: 

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; 
}
Christopher W. Allen-Poole
You are right! Thanks :D
azamsharp
This article says that by using prototype you will add the properties to the instance of the Object => http://www.javascriptkit.com/javatutors/proto2.shtml
azamsharp
I can't speak for all browsers' implementations of JavaScript, but my experience has shown that modifying the prototype does not actually modify the instances. Yes, prototype modifications are accessible to members of that class, but they are not the same as assigning member variables.
Christopher W. Allen-Poole