C
cbetz.sicom
I am trying to serialize/unserialize objects while preserving their
(proto)type. After a lot of looking I discovered that I can take a
generic object and modify its __proto__ property so that it becomes
the object I want.
However, what I am *really* looking for is a way to automatically
preserve the prototype when serializing an object--even when that
object contains other objects. Specifically I want to be able to take
some JSON representing an object and have it automatically converted
into a javascript object with the correct prototype, not just some
generic object.
Let me explain...
function Bar() {
this.hello = function() { alert("hello from a Bar");}
}
function Foo() {
this.stuff=new Array();
this.stuff.push(new Bar());
this.hello = function() { alert("hello from a Foo"); }
}
var f=new Foo();
var anonymous_foo=JSON.parse(JSON.stringify(f));
Problem:
anonymous_foo.hello() will be undefined unless I do
anonymous_foo.__proto__ = new Foo()
Bigger problem:
anonymous_foo.stuff[0].hello() will also be undefined unless I do
something similar. However, what I if I don't know that that that
stuff[0] is a Bar... what if it is a Baz or something else?
Is there any issue with modifying JSON.parse/stringify so that it can
work with __proto__?
(proto)type. After a lot of looking I discovered that I can take a
generic object and modify its __proto__ property so that it becomes
the object I want.
However, what I am *really* looking for is a way to automatically
preserve the prototype when serializing an object--even when that
object contains other objects. Specifically I want to be able to take
some JSON representing an object and have it automatically converted
into a javascript object with the correct prototype, not just some
generic object.
Let me explain...
function Bar() {
this.hello = function() { alert("hello from a Bar");}
}
function Foo() {
this.stuff=new Array();
this.stuff.push(new Bar());
this.hello = function() { alert("hello from a Foo"); }
}
var f=new Foo();
var anonymous_foo=JSON.parse(JSON.stringify(f));
Problem:
anonymous_foo.hello() will be undefined unless I do
anonymous_foo.__proto__ = new Foo()
Bigger problem:
anonymous_foo.stuff[0].hello() will also be undefined unless I do
something similar. However, what I if I don't know that that that
stuff[0] is a Bar... what if it is a Baz or something else?
Is there any issue with modifying JSON.parse/stringify so that it can
work with __proto__?