creational.prototype.copy_through_serialization.js
creational.prototype.copy_through_serialization.js
{
constructor(streetAddress, city, country) {
this.streetAddress = streetAddress;
this.city = city;
this.country = country;
}
toString()
{
return `Address: ${this.streetAddress}, ` +
`${this.city}, ${this.country}`;
}
}
class Person
{
constructor(name, address)
{
this.name = name;
this.address = address; //!
}
toString()
{
return `${this.name} lives at ${this.address}`;
}
greet()
{
console.log(
`Hi, my name is ${this.name}, ` +
`I live at ${this.address.toString()}`
);
}
}
class Serializer
{
constructor(types){
this.types = types;
}
markRecursive(object)
{
// anoint each object with a type index
let idx = this.types.findIndex(t => {
return t.name === object.constructor.name;
});
if (idx !== -1)
{
object['typeIndex'] = idx;
reconstructRecursive(object)
{
if (object.hasOwnProperty('typeIndex'))
{
let type = this.types[object.typeIndex];
let obj = new type();
for (let key in object)
{
if (object.hasOwnProperty(key) && object[key] != null) {
obj[key] = this.reconstructRecursive(object[key]);
}
}
delete obj.typeIndex;
return obj;
}
return object;
}
clone(object)
{
this.markRecursive(object);
let copy = JSON.parse(JSON.stringify(object));
return this.reconstructRecursive(copy);
}
}
jane.name = 'Jane';
jane.address.streetAddress = '321 Angel St';
john.greet();
// this won't work
// jane.greet();
jane.name = 'Jane';
jane.address.streetAddress = '321 Angel St';
console.log(john.toString());
console.log(jane.toString());