Recovering an object serialized in JSON

In my web application, I serialize storage objects using JSON.stringify (), as described here . This is great, and I can easily recreate objects from JSON strings, but I lose all the methods of the objects. Is there an easy way to add these methods back to the objects I'm viewing - possibly using prototyping, which I'm not too familiar with?

Or is it just a case of creating my own complex function for this?

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

Object.inheritMethods(AnotherObject); 
+6
source share
2 answers

Once you have an object after calling JSON.parse, you have many options. Here are some examples.

  • Mixin

    There are many methods for this that this article describes well. However, here is a simple example that does not require any new language features. Remember that an object is essentially just a map, so JS makes it easy to add additional objects to the 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); 
  • Prototypic

    Use the Object.create method that Felix mentioned. Since this is only offered in ES5, you can use shim to ensure its availability.

+2
source

Old question, but I found it when looking for this problem today. I found the solution elsewhere and increased speed (ES6):

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

0
source

Source: https://habr.com/ru/post/895969/


All Articles