I know how to parse a JSON String and turn it into a JavaScript Object. You can use eval() or jQuery.parseJSON().
That's great, but how can I take that JavaScript Object and turn it into a particular JavaScript Object (i.e. with a certain prototype)?
For example, suppose you have:
function Foo()
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = jQuery.parseJSON({"a":4, "b": 3});
//Something to convert fooJSON into a Foo Object
//....... (this is what I am missing)
alert(fooJSON.test() ); //Prints 12
Again, I am not wondering how to convert a JSON string into a generic JavaScript Object. I want to know how to convert a JSON string into a "Foo" Object. That is, my Object should now have a function 'test' and properties 'a' and 'b'.
UPDATE After doing some research, I thought of this...
function Object.cast(rawObj, constructor)
{
var obj = new constructor();
for(var i in rawObj)
obj.i = rawObj.i;
return obj;
}
var fooJSON = Object.cast(jQuery.parseJSON({"a":4, "b": 3}), Foo);
Will that work?