Open In App

How to Dynamically Serialise & Restore ES6 Class Types in JavaScript ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Dynamically serializing and restoring ES6 class types in JavaScript refers to the process of converting instances of ES6 classes into a format (e.g., JSON) that can be stored or transmitted, and then reconstructing those instances from the serialized data, preserving their class structure and behavior.

These are the following ways:

Approach 1: Using JSON.stringify() and JSON.parse()

Using JSON.stringify() converts an object to a JSON string. this is how serialization occurs. JSON.parse() then restores the object from the string. It’s simple but doesn’t directly handle class types.

Syntax:

JSON.stringify(value, replacer, space);
JSON.parse( string, function );

Example: We Serialize and restore the Person class instance result. Serializes with JSON.stringify() and restores with JSON.parse(), ensuring proper class type restoration.

Javascript




class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}
 
const result = new Person('Rahul', 15);
 
const serializedResult = JSON.stringify(result);
 
const deserializedResult = JSON.parse(serializedResult,
    (key, value) => key === ''
        && value && value.__class === 'Person' ?
        new Person(value.name, value.age) : value
);
 
console.log(deserializedResult);


Output

{ name: 'Rahul', age: 15 }

Approach 2: Using Object.assign() and Object.setPrototypeOf():

In this approach we are using Object.assign() copies properties of the serialized object. Object.setPrototypeOf() sets prototype of deserialized object. Together, they dynamically serialize and restore class types, maintaining object structure and behavior.

Syntax:

Object.assign(target, ...sources);
Object.setPrototypeOf(obj, prototype);

Example: We serializes the Person object using Object.assign() and restores the class type using Object.setPrototypeOf().

Javascript




class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}
 
const Result = new Person('Rohit', 45);
 
const serializedResult = Object.assign(Object.
    create(Object.getPrototypeOf(Result)), Result);
 
const deserializedResult = Object
    .setPrototypeOf(serializedResult, Person.prototype);
 
console.log(deserializedResult);


Output

Person { name: 'Rohit', age: 45 }


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads