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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With