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?

4
  • 1
    You do realize you are reading back a string. Commented Jan 10, 2013 at 5:04
  • Yes, you will need to create a new instance and assign the values you parsed from the JSON serialisation. Commented Jan 10, 2013 at 5: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. Commented Jan 10, 2013 at 5:10
  • @Musa, sorry, ignore me. While creating this example, I forgot to do the JSON.parse, so yes, you are right! Commented Jan 10, 2013 at 5:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.