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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.