开发者

JQuery JSON Plugin toJSON a Custom Object

开发者 https://www.devze.com 2022-12-09 23:43 出处:网络
I am using the JQuery json plugin and trying to convert a custom object to JSON using the toJSON function. Here is the object:

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.


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; 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号