Reuse 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 was to be able to call "showFullName" on the page. Although I understand that JS has no objects, it should have some way of saying that something needs to be handled in a certain way, like casting thePersonup to Person.

+5
source share
5 answers

As far as I know, the best way to do this is to first create a vanilla object and then overlay the data on it using something like jQuery extend , i.e.

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

, extend, , . .

+2

.

JSON .

+2

, , , Javascript. , , :

var data = JSON.parse(jsonString);
var person = new Person(data);

:

var person = new Person({ FirstName: "xx", LastName: "xxx"});

(nb - $.extend - , , , , , ).

+2

, JS , - - .

. JS ; - . AFAIK , , . , , Javascript . , JS .

JS.

x.someMethod()

someMethod , x, x. .

JSON.parse object literal. , , , , .

0

-, , . " ", . , , "" . , http://backbonejs.org/

0

All Articles