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);
Once you have your object after calling JSON.parse, you have many options. Here's a few examples.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With