Reputation: 16055
Let's say I have this object
Function Person(name){
this.name = name;
this.kill = function(){
console.log(this.name + ' is now dead.');
}
}
Then I do this
var Tom = new Person('Tom');
var SerializedTom = JSON.stringify(Tom);
delete Tom // figuratively, Tom doesn't exist anymore
And now I want to recreate Tom
var NewTom = new Person();
NewTom = JSON.parse(SerializedTom);
Basically this is what I want to do, but then the kill
function is lost. My question is how can I insert the data from the serialized object into the new object while maintaining it's functions?
Upvotes: 0
Views: 55
Reputation: 20043
I'd write methods that handle the serialization. This allows full control over the state of the class as well as the deserialization and avoids potentially copying over fields that aren't supposed to be members of your class. It's a bit more effort than T.J. Crowder's solution, which is more dynamic, but it has more control and in my opinion is a cleaner approach. Both are fine, though.
function Person( name ) {
this.name = name;
}
Person.prototype.kill = function() {
console.log( this.name + " is now dead." );
};
// static method on the class where you receive your JSON object
// and create the instance of Person and set it up
// the way you want.
Person.fromJson = function( json ) {
return new Person( json.name );
};
var Tom = Person.fromJson( JSON.parse( JSON.stringify( new Person( "Tom" ) ) ) );
Upvotes: 1
Reputation: 1075129
There's no out-of-the-box answer. One option is to modify your Person
object so it can accept a data object, and then copy everything on the data object:
function Person(data){
var key;
for (key in data) {
this[key] = data[key];
}
this.kill = function(){
console.log(this.name + ' is now dead.');
};
}
// Usage
var Tom = new Person(JSON.parse(SerializedTom));
You can support both with a type check:
function Person(data){
var key;
if (typeof data === "object") {
for (key in data) {
this[key] = data[key];
}
}
else { // assume string
this.name = data;
}
this.kill = function(){
console.log(this.name + ' is now dead.');
};
}
Side note:
You can put kill
on the prototype that Person
assigns to instances:
function Person(data){
var key;
if (typeof data === "object") {
for (key in data) {
this[key] = data[key];
}
}
else { // assume string
this.name = data;
}
}
Person.prototype.kill = function(){
console.log(this.name + ' is now dead.');
};
Upvotes: 1