-
-
Save esshka/0c435533f8a99bc8e6066114c31d54e1 to your computer and use it in GitHub Desktop.
serialize/deserialize es6 class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyChart { | |
constructor(){ | |
this.foo = "foo"; | |
return this; | |
} | |
sayFoo(){ | |
console.log("saying", this.foo); | |
return this; | |
} | |
} | |
function Base(){ | |
this.foo1 = "bar1"; | |
return this; | |
} | |
function Extended(){ | |
this.foo2 = "bar2"; | |
return this; | |
} | |
Extended.prototype = new Base(); | |
Extended.prototype.constructor = Extended; | |
Extended.prototype.sayFoo = function(){ | |
console.log('saying', this.foo1, this.foo2); | |
} | |
// Map/Reduce Serializer/Deserializer | |
const serializer = proto => Object.getOwnPropertyNames(proto).map(key=>[key, Object.getOwnPropertyDescriptor(proto, key).value.toString()]); | |
const deserializer = proto => proto.reduce((k,p) => Object.defineProperty(k, p[0], {value:~p[1].indexOf('function') ? Function.apply(null, [`return ${p[1]}`])() : p[1]}), {}); | |
const factory = proto => Object.create(deserializer(serializer(proto))); | |
//let instanceMyChart = factory(MyChart.prototype); | |
let instanceMyChart = factory(Extended.prototype); | |
instanceMyChart.constructor().sayFoo(); | |
// Note: An alternative is serialize/deserialize an instance as below | |
/* | |
class ES6ClassSerializer { | |
static encode(instance) { | |
const _result = {}; | |
Object.getOwnPropertyNames(instance).forEach(prop => _result[prop] = instance[prop]); | |
Object.getOwnPropertyNames(Object.getPrototypeOf(instance)).forEach(method => _result[method] = instance[method]); | |
const replacer = (key, value) => typeof value === 'function' ? value.toString() : value; | |
return JSON.stringify(_result, replacer, 2); | |
} | |
static decode(serializedObject) { | |
const revivier = (key, value) => typeof value === 'string' && value.indexOf('function ') === 0 ? | |
Function.apply(null, [`return ${value}`])() : value; | |
return JSON.parse(serializedObject, revivier); | |
} | |
} | |
const instanceMyChart = new MyChart(); | |
const se_instanceMyChart = ES6ClassSerializer.encode(instanceMyChart); | |
const de_instanceMyChart = ES6ClassSerializer.decode(se_instanceMyChart); | |
de_instanceMyChart.sayFoo(); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment