admin管理员组

文章数量:1244223

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?

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?

Share Improve this question edited Mar 12, 2012 at 14:00 Henrik Hansen 2,1901 gold badge14 silver badges19 bronze badges asked Mar 12, 2012 at 13:54 user208662user208662 11k27 gold badges76 silver badges86 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 7

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.

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 ) );
   }

}

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 pleteObject = Object.assign(new MyObject(), mo);

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

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.

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

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

http://www.json/js.html

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

Serializing methods is not a standard and can use a lot of place.

Here an alternative, to recover an object serialized with JSON.stringify :

function recoverObject (target, source) {
  for (const key of Object.getOwnPropertyNames(source)) {
    const value = source[key]
    if (value === Object(value)) {
      target[key] = classInstanceByName(key)
      recoverObject(target[key], value)
    } else {
      target[key] = value
    }
  }
}

And bellow there is an example of classInstanceByName

function classInstanceByName (key) {
  const map = {
    attacks: [],
    bag: new Bag(),
    currentPlace: new Place(),
    currentScenario: new Scenario({}),
    fight: new Fight(),
    nextScenario: new Scenario({})
  }
  return map[key] || new Object()
}

There is two downside :

  • All your variables that share the same name must have the same class
  • You must have patible constructor for each class

本文标签: jsonJavaScript Serialization and MethodsStack Overflow