Search code examples
javascriptjsonserializationmethodsjstorage

JavaScript: Keep methods after serialization


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?


Solution

  • You could change your TestObject constructor function so that it can accept an object containing optional initial values for all its properties:

    function TestObject(properties) {
        this.lang = (properties && !(properties.lang === undefined)) ? properties.lang : "English";
    }
    

    And then use your deserialised object to create a new object using the constructor function, instead of using the deserialised object directly:

    var test2 = new TestObject( $.parseJSON(JSON.stringify(test1)) );
    

    This seems to work: http://jsfiddle.net/wubfckez/