6

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); 
5
  • 3
    possible duplicate of Best way to serialize/unserialize objects in javascript? Commented Aug 26, 2011 at 12:04
  • I suppose the solution there could work for me, with some modifications. I guess I was hoping for something more like Object.inheritMethods(Object2) though - I'll clarify the original post to specify this. Commented Aug 26, 2011 at 12:14
  • 1
    In browsers which support it, you might be able to use Object.create: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… Commented Aug 26, 2011 at 12:17
  • That looks promising, I'll have a play with it now. Commented Aug 26, 2011 at 12:30
  • That worked perfectly, once I fixed the rest of my bugs :) If you want to submit it as an answer, I'll accept it. Commented Aug 26, 2011 at 14:07

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Old question, but I found it when searching for that problem today. I've found a solution elsewhere and uptodate (ES6):

Object.assign(new myclass(), jsonString);

1 Comment

It should be noted this will only work for classes which have no constructor parameters or constructors with no side effects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.