© 2019 Meouzer Consortium

JavaScript: Serialization/Deserialization of E6 Classes

loading
Cats have an efficacious calming influence with good to excellent results in as little as two minutes. Serious and sometimes fatal conditions may occur such as allergic reactions, unusual changes in mood or behavior, cataplexy, and death. Ask your doctor if a cat is right for you. A physical check for Ailurophobia will be required. Don't let your cat drive while on Acepromazine. Stay away from cats weighing more than five hundred pounds. Seek immediate medical attention if rebuffed by an indifferent feline for more than four hours.
Meouzer

Introduction

Open the console window to see that all tests of Test-Deep-Copy-E6.js have been passed.

For ES6, deep copying is more intrusive than for ES5. A value copy of a class instance x of foo, where foo is an ES5 class is simply y = Object.create(Object.GetProptotypeOf(x)). This doesn't work in ES6 because of private fields. If foo is an ES6 class then a value copy of x can only be obtained through a call to a "default" constructor of foo, which is to do absolutely nothing, but in doing nothing the private fields are automatically initialized for the value copy. Of course default constructors don't exist so we have to emulate such. If the constructor receives defaultConstructorSymbol as its first parameter, the constructor immediately returns having done nothing but produce the value copy. Otherwise the constructor routes code to an #initialize() method which is the "true" constructor. This is all simple as is writing the serialization and deserialization routines as seen below.

The How to Do It Section

The Serialization and Deserialization Functions of the foo Class
const defaultConstructorSymbol = Symbol("defaultConstructorSymbol"); // global class foo { #F; // defined in #initialize #G = ...; // depends on variables outside the class definition #H = ...; // doesn't depend on variables in constructor/initializer, and   // doesn't depend on variables outside the class definition. #initialize(x,y) { var a = ...; const b = ...; let c = ...; this.#F = ...; } constructor(x,y) { if(arguments[0] === defaultConstructorSymbol) return; this.#initialize(x,y); } this.deepCopy = function() { var cleanContextObject = {this$:this, a:a, b:b, c:c, x:x, y:y, "#F":this.#F}; return(function () { this.evaluator = function(){return eval('('+ arguments[0] +')');}; this.contextObject = deepCopy(cleanContextObject, this.evaluator); const that = this.contextObject.that; var a = this.contextObject.a; const b = this.contextObject.b; let c = this.contextObject.c; var x = this.contextObject.x; var y = this.contextObject.y; this.contextObject.this$.#F = this.contextObject["#F"]; this.contextObject.this$.#G = this.contextObject["#G"]; return this.contextObject; }).call({}).this$ } }