Bug Tracker

Opened 7 years ago

Closed 7 years ago

Last modified 7 years ago

#12762 closed bug (invalid)

jQuery's JSON serializer serializes prototype's values

Reported by: Sense545 Owned by: Sense545
Priority: undecided Milestone: None
Component: unfiled Version: 1.8.2
Keywords: Cc:
Blocked by: Blocking:

Description

var test = function test() { this.foo = "bar"; };
test.prototype.bar = "foo";
$.ajax({ url: "/", type: "POST", dataType: "json", data: new test() })

http://stackoverflow.com/questions/12369543/why-is-json-stringify-not-serializing-prototype-values

http://es5.github.com/#JO

Change History (5)

comment:1 Changed 7 years ago by mikesherov

Owner: set to Sense545
Status: newpending

Hi, and thanks for contributing! Sure, that's definitely a bug, but seems like it's an edge case that doesn't reflect a real world usage. Could you be specific in how or why this would ever come in a real world example so I can get a sense of priority here?

comment:2 Changed 7 years ago by trac-o-bot

Resolution: invalid
Status: pendingclosed

Because we get so many tickets, we often need to return them to the initial reporter for more information. If that person does not reply within 14 days, the ticket will automatically be closed, and that has happened in this case. If you still are interested in pursuing this issue, feel free to add a comment with the requested information and we will be happy to reopen the ticket if it is still valid. Thanks!

comment:3 Changed 7 years ago by Sense545

Hi. Lets say i have a

function Person(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
}
Person.prototype = {
    minAge: 16,
    isOfAge: function() { return this.age >= this.minAge; }
}

If I then try to send an instance of this person to the server for further processing, it would send the "minAge" property as well. This is only the case for jQuery's built in JSON serializer.

I am currently working around this by always using JSON.stringify(person) and then pass the JSON string to $.ajax.

This is not mission critical, but is strange behavior and can probably be fixed by adding a Object.hasOwnProperty where the object's keys are looped. ( I have not looked at the jQuery source to confirm this )

comment:4 Changed 7 years ago by Rick Waldron

That would break any existing code that relied on the behaviour. Also, the docs clearly state "plain object" http://api.jquery.com/jquery.param/

comment:5 Changed 7 years ago by dmethvin

And to clarify, jQuery does not have a JSON serializer/stringifier, only a parser ($.parseJSON). Argments passed to $.ajax via the data property are serialized using the standard form-encoding rules and should be in a plain object, not in a constructed object, as rwaldron and the docs say.

Note: See TracTickets for help on using tickets.