Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reapply JS Prototype functions after deserialization

Given the following code:

function Person(firstName, lastName) {
    this.FirstName = firstName;
    this.LastName = lastName;
}

Person.prototype.showFullName = function() {
    return this.FirstName + " " + this.LastName;
};

var person = new Person("xx", "xxxx");
var jsonString = JSON.stringify(person);

var thePerson = JSON.parse(jsonString);

My goal here would be to be able to call "showFullName" on thePerson. While I understand that JS does not really have objects, it must have some way of being able to say something should be treated a certain way, like casting thePerson to a Person.

like image 535
xximjasonxx Avatar asked Jun 13 '12 14:06

xximjasonxx


1 Answers

To my knowledge the best way to do this is to construct a vanilla object first and then plop the data onto it using something like jQuery's extend, ie.

var thePerson = new Person(); // and make sure the constructor gracefully handles no arguments
jQuery.extend(thePerson, JSON.parse(stringData));

As mentioned below, you don't need to use extend if you're only creating a shallow copy, which you are here. You can just loop through the properties of the parsed data and copy them onto your target object.

like image 87
Dan Avatar answered Oct 05 '22 23:10

Dan