I am stuck with a greater JavaScript application (using jQuery Mobile) with big parts of the program logic realized already. Now I want to add serialization to it (using a plugin called JStorage). In this code example, I stringify an object to JSON and then turn it into an object again (all without JStorage), but the methods I added to the original object get lost as in this code:
function TestObject() {
this.lang = "English";
}
// This is the method I want to keep
TestObject.prototype.showLang = function() {
console.log(this.lang)
};
var test1 = new TestObject();
var test2 = $.parseJSON(JSON.stringify(test1)); // After save and reload
test1.showLang(); // This works
test2.showLang(); // This causes an error
The problem has one other constraint: In the code, I often use the point operator to call functions as in test1.showLang(). I know I could add a "global" function like this, it works with the original as well as with the copy:
function showLang(obj) {
console.log(obj.lang);
}
But then I'd have to change each and every existing call to the function from test1.showLang() to showLang(test1) which - in my real project - I would have to do hundreds of times within the entire code. So is there an easier solution how I can use my existing functions on objects after serialization?