I have many JavaScript objects in my application, something like:
function Person(age) {
this.age = age;
this.isOld = function (){
return this.age > 60;
}
}
// before serialize, ok
var p1 = new Person(77);
alert("Is old: " + p1.isOld());
// after, got error Object #<Object> has no method 'isOld'
var serialize = JSON.stringify(p1);
var _p1 = JSON.parse(serialize);
alert("Is old: " + _p1.isOld());
See in JS Fiddle.
My question is: is there a best practice/pattern/tip to recover my object in same type it was before serialization (instances of class Person, in this case)?
Requirements that I have:
- Optimize disk usage: I have a big tree of objects in memory. So, I don’t want to store functions.
- Solution can use jQuery and another library to serialize/unserialize.
JSON has no functions as data types. You can only serialize strings, numbers, objects, arrays, and booleans (and
null)You could create your own
toJsonmethod, only passing the data that really has to be serialized:Similar for deserializing:
The usage would be:
To reduce the amount of work, you could consider to store all the data that needs to be serialized in a special “data” property for each
Personinstance. For example:then serializing and deserializing is merely calling
JSON.stringify(this.data)and setting the data of an instance would beinstance.data = JSON.parse(json).This would keep the
toJsonandfromJsonmethods simple but you’d have to adjust your other functions.Side note:
You should add the
isOldmethod to the prototype of the function:Otherwise, every instance has it’s own instance of that function which also increases memory.