I have an app that allows users to generate objects, and store them (in a MySQL table, as strings) for later use. The object could be :
function Obj() {
You can indeed create an empty instance and then merge the instance with the data. I recommend using a library function for ease of use (like jQuery.extend
).
You had some errors though (function ... = function(...)
, and JSON requires keys to be surrounded by "
).
http://jsfiddle.net/sc8NU/1/
var data = '{"label": "new object"}'; // JSON
var inst = new Obj; // empty instance
jQuery.extend(inst, JSON.parse(data)); // merge
Note that merging like this sets properties directly, so if setLabel
is doing some checking stuff, this won't be done this way.
JavaScript is prototype based programming language which is classless language where object orientation achieved by process of cloning existing objects that serve as prototypes.
Serializing JSON would be considering any methods, for instance if you have an object
var x = {
a: 4
getText: function() {
return x.a;
}
};
You will get just { a:4 }
where getText
method is skipped by the serializer.
I ran into this same trouble a year back and I had to maintain a separate helper class for each of my domain object and used $.extend() it to my deserialized object when need, just more like having methods to a base class for the domain objects.