Skip to content Skip to sidebar Skip to footer

Javascript Json.stringify Doesn't Handle Prototype Correctly?

I've been initializing my reusable classes like this (constructor is usually a copy-constructor): function Foo() {} Foo.prototype.a = '1'; Foo.prototype.b = '2'; Foo.prototype.c =

Solution 1:

Properties on an object's prototype (that is, the prototype of its constructor) are readable via a reference to an the object:

functionConstructor() { }
Constructor.prototype.a = "hello world";

var x = newConstructor();
alert(x.a); // "hello world"

However, those properties really are "stuck" on the prototype object:

alert(x.hasOwnProperty("a")); //false

The JSON serializer only pays attention to properties that directly appear on objects being processed. That's kind-of painful, but it makes a little sense if you think about the reverse process: you certainly don't want JSON.parse() to put properties back onto a prototype (which would be pretty tricky anyway).

Solution 2:

your answer lies Why is JSON.stringify not serializing prototype values?

JSON.stringify only does "own" properties.

In your first example: prototype members are being set, and then calling Stringify on the object itself, which does not have its own properties.

In your second: this.a will climb the chain until it finds the property

In the third: You are setting properties directly on the object and not its prototype

Post a Comment for "Javascript Json.stringify Doesn't Handle Prototype Correctly?"