0

Possible Duplicate:
Easiest way to convert json data into objects with methods attached?
Casting plain objects to function instances (“classes”) in javascript

I have an object as follows:

var Person = function(name, age) {
  this.name = name,
  this.age = age;
}

Person.prototype.talk = function(message) {
    console.log(message);
}

I create objects as follows:

var person = new Person("Test", 20);

These objects are then saved as JSON (stringify) in browser's local storage

When I read the object back, I get the data, but I don't get the methods attached, i.e. talk() is not available as a method any more. How do I attach them again?

window.localStorage["person"] = JSON.stringify(new Person('Test', 20));
var person = window.localStorage["person"];
person.talk("Hello");

The error I get is

Uncaught TypeError: Object {"name":"Test","age":20} has no method 'talk' 

Obvious, right? But how do I tell that this is a Person object? Or should I just copy the attributes from the read object onto a new Person object, is that the only way?

Community
  • 1
  • 1
aishwarya
  • 1,970
  • 1
  • 14
  • 22
  • 1
    You do realize you are reading back a string. – Musa Jan 10 '13 at 05:04
  • Yes, you will need to create a new instance and assign the values you parsed from the JSON serialisation. – Bergi Jan 10 '13 at 05:05
  • @Musa, yes so I thought, but if you look at what comes back, it looks like a JSON object and not a string! Anyways, I guess I will have to live with copying of attributes. – aishwarya Jan 10 '13 at 05:10
  • @Musa, sorry, ignore me. While creating this example, I forgot to do the JSON.parse, so yes, you are right! – aishwarya Jan 10 '13 at 05:24

1 Answers1

1

Or should I just copy the attributes from the read object onto a new Person object, is that the only way?

Yes, make a PersonFactory or use a similar design pattern to construct a new Person object from the json data representing a Person.

Travis J
  • 81,153
  • 41
  • 202
  • 273