JSON has no functions as data types. You can only serialize strings, numbers, objects, arrays, and booleans (and null
)
You could create your own toJson
method, only passing the data that really has to be serialized:
Person.prototype.toJson = function() {
return JSON.stringify({age: this.age});
};
Similar for deserializing:
Person.fromJson = function(json) {
var data = JSON.parse(json); // Parsing the json string.
return new Person(data.age);
};
The usage would be:
var serialize = p1.toJson();
var _p1 = Person.fromJson(serialize);
alert("Is old: " + _p1.isOld());
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 Person
instance. For example:
function Person(age) {
this.data = {
age: age
};
this.isOld = function (){
return this.data.age > 60 ? true : false;
}
}
then serializing and deserializing is merely calling JSON.stringify(this.data)
and setting the data of an instance would be instance.data = JSON.parse(json)
.
This would keep the toJson
and fromJson
methods simple but you'd have to adjust your other functions.
Side note:
You should add the isOld
method to the prototype of the function:
Person.prototype.isOld = function() {}
Otherwise, every instance has it's own instance of that function which also increases memory.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…