3

I am new to "object-oriented" JavaScript. Currently, I have an object that I need to pass across pages. My object is defined as follows:

function MyObject() { this.init(); }
MyObject.prototype = {
    property1: "",
    property2: "",

    init: function () {
        this.property1 = "First";
        this.property2 = "Second";
    },

    test: function() {
      alert("Executing test!");
    }
}

On Page 1 of my application, I am creating an instance of MyObject. I am then serializing the object and storing it in local storage. I am doing this as shown here:

var mo = new MyObject();
mo.test();                                    // This works
window.localStorage.setItem("myObject", JSON.stringify(mo));

Now, on Page 2, I need get that object and work with it. To retrieve it, I am using the following:

var mo = window.localStorage.getItem("myObject");
mo = JSON.parse(mo);
alert(mo.property1);    // This shows "First" as expected.
mo.test();              // This does not work. In fact, I get a "TypeError"  that says "undefined method" in the consol window.

Based on the outputs, it looks like when I serialized the object, somehow the functions get dropped. I can still see the properties. But I can't interact with any of my functions. What am I doing wrong?

Henrik Hansen
  • 2,180
  • 1
  • 14
  • 19
user208662
  • 10,869
  • 26
  • 73
  • 86

6 Answers6

6

JSON doesn't serialize functions.

Take a look at the second paragraph here.

If you need to preserve such values, you can transform values as they are serialized, or prior to deserialization, to enable JSON to represent additional data types.

In other words, if you really want to JSONify the functions, you can convert them to strings before serializing:

mo.init = ''+mo.init;
mo.test = ''+mo.test;

And after deserializing, convert them back to functions.

mo.init = eval(mo.init);
mo.test = eval(mo.test);

However, there should be no reason to do that. Instead, you can have your MyObject constructor accept a simple object (as would result from parsing the JSON string) and copy the object's properties to itself.

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
5

Functions can not be serialized into a JSON object.

So I suggest you create a separate object (or property within the object) for the actual properties and just serialize this part. Afterwards you can instantiate your object with all its functions and reapply all properties to regain access to your working object.

Following your example, this may look like this:

function MyObject() { this.init(); }
MyObject.prototype = {
    data: {
      property1: "",
      property2: ""
    },

    init: function () {
        this.property1 = "First";
        this.property2 = "Second";
    },

    test: function() {
      alert("Executing test!");
    },


   save: function( id ) {
     window.localStorage.setItem( id, JSON.stringify(this.data));
   },
   load: function( id ) {
     this.data = JSON.parse( window.getItem( id ) );
   }

}
Sirko
  • 72,589
  • 19
  • 149
  • 183
1

To avoid changing the structure, I prefer to use Object.assign method on object retrieval. This method merge second parameter object in the first one. To get object methods, we just need an empty new object which is used as the target parameter.

var mo = window.localStorage.getItem("myObject");
// this object has properties only
mo = JSON.parse(mo);
// this object will have properties and functions
var completeObject = Object.assign(new MyObject(), mo);

Note that the first parameter of Object.assign is modified AND returned by the function.

Nicolas Janel
  • 3,025
  • 1
  • 28
  • 31
1

it looks like when I serialized the object, somehow the functions get dropped... What am I doing wrong?

Yes, functions will get dropped when using JSON.stringify() and JSON.parse(), and there is nothing wrong in your code.

To retain functions during serialization and deserialization, I've made an npm module named esserializer to solve this problem -- the JavaScript class instance values would be saved during serialization on Page 1, in plain JSON format, together with its class name information:

var ESSerializer = require('esserializer');

function MyObject() { this.init(); }
MyObject.prototype = {
    property1: "",
    property2: "",

    init: function () {
        this.property1 = "First";
        this.property2 = "Second";
    },

    test: function() {
      alert("Executing test!");
    }
}
MyObject.prototype.constructor=MyObject; // This line of code is necessary, as the prototype of MyObject has been overridden above.

var mo = new MyObject();
mo.test();                                    // This works
window.localStorage.setItem("myObject", ESSerializer.serialize(mo));

Later on, during the deserialization stage on Page 2, esserializer can recursively deserialize object instance, with all types/functions information retained:

var mo = window.localStorage.getItem("myObject");
mo = ESSerializer.deserialize(mo, [MyObject]);
alert(mo.property1);    // This shows "First" as expected.
mo.test();              // This works too.
shaochuancs
  • 15,342
  • 3
  • 54
  • 62
0

That's because JSON.stringify() doesn't serialize functions i think.

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
0

You're right, functions get dropped. This page might help:

http://www.json.org/js.html

"Values that do not have a representation in JSON (such as functions and undefined) are excluded."

JTeagle
  • 2,196
  • 14
  • 15