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?