1

I think about saving objects using JSON.stringify and later load them again. The "stringification" works well of course, however I am not sure how I would set the prototype/class of an object.

VisioN
  • 143,310
  • 32
  • 282
  • 281
user1680104
  • 8,437
  • 4
  • 22
  • 27

1 Answers1

1

You can use .toJSON and reviver callback to achieve this.

Here is the scheme:

function Person() {
    this.name = "name";
    this.age = "age";
}

Person.prototype.toJSON = function() {
            //Define this for other classes as well
    return {__class__: "Person", name: this.name, age: this.age};
};

function reviver( key, value ) {
        if( typeof value == "object" && value.__class__ ) {
            var ret = new window[value.__class__];
            for( var k in value ) {
                if( k === "__class__" ) continue;
                ret[k] = value[k];
            }
            return ret;
        }
        return value;
}

var a = new Person(),
    b = new Person();

var json = JSON.stringify( [a,b] );

var decoded = JSON.parse( json, reviver);

console.log( decoded ); //[Person, Person] I.E. array of Person instances instead of plain objects

in this simplified scheme, the class must be global.

Esailija
  • 138,174
  • 23
  • 272
  • 326