the reason I am asking this question is because I want to use LocalStorage for my objects. And as you might know, when using LocalStorage you have to JSON.stringify the objects and then parse them back to javascript objects.
I am trying to JSON.stringify an object with methods and then parse it back but all I get is an empty object.
Please take a look at this code.
Person.js
function Person(name, telePhone) {
this.getName = function () {
return name;
}
this.setName = function (_name) {
name = _name;
}
this.getTelePhone = function () {
return telePhone;
}
this.setTelePhone = function (_telePhone) {
telepPhone = _telePhone;
}
};
Javascript.js
window.onload = function () {
var name = "John";
var telePhone = "073-2335662";
var personObject = new Person(name, telePhone);
console.log(personObject);
// returns: Person
console.log(personObject.getName());
//returns: John
var test = JSON.stringify(personObject);
var newPersonObject = JSON.parse(test);
console.log(newPersonObject);
//returns: Object
console.log(newPersonObject.getName());
//returns: Uncaught TypeError: Object #<Object> has no method 'getName'
};
Any suggestions why this Person object after JSON.stringify and JSON.parse is empty and loses all it's methods?