Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rebuilding an object serialized in JSON

In my web app, I'm serializing objects for storage using JSON.stringify() as described here. This is great, and I can easily re-create the objects from the JSON strings, but I lose all of the objects' methods. Is there a simple way to add these methods back to the objects that I'm overlooking - perhaps involving prototyping, something I'm not overly familiar with?

Or is it just a case of creating an elaborate function of my own for doing this?

Edit: Ideally, I'm looking for something like:

Object.inheritMethods(AnotherObject);
like image 637
Jim Avatar asked Aug 26 '11 12:08

Jim


1 Answers

Once you have your object after calling JSON.parse, you have many options. Here's a few examples.

  1. Mixin

    There are many techniques for doing this, which this article describes nicely. However, here's a simple example that doesn't require any new language features. Remember that an object is essentially just a map, so JS makes it easy to add additional properties to an object.

    var stuffToAdd = function() {
        this.name = "Me";        
    
        this.func1 = function() {
            print(this.name);
        }
    
        this.func2 = function() {
            print("Hello again");
        }
    }
    
    var obj = JSON.parse("{}");
    stuffToAdd.call(obj);
    
  2. Prototypical

    Use the Object.create method that Felix mentioned. Since this is only offered in ES5, you may want to use a shim to guarantee its availability.

like image 61
Steve Avatar answered Oct 13 '22 17:10

Steve