Created
January 27, 2017 18:14
-
-
Save XoseLluis/72c96c2b4b5bf0587a7c03bcfd38d7f4 to your computer and use it in GitHub Desktop.
Typed Serialization in javascript
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
function getFunctionFromStringName(functionNameSt){ | |
eval("var func = " + functionNameSt + ";"); | |
return func; | |
} | |
class TypedSerializer{ | |
static serialize(obj){ | |
let aux = { | |
typeName: obj.constructor.name, | |
data: obj | |
}; | |
return JSON.stringify(aux); | |
} | |
static deserialize(text){ | |
let aux = JSON.parse(text); | |
let constructorFunc = getFunctionFromStringName(aux.typeName); | |
//this does not work, Object.create takes a map of property descriptors | |
//return Object.create(constructorFunc.prototype, aux.data); | |
var obj = Object.create(constructorFunc.prototype); | |
Object.assign(obj, aux.data); | |
return obj; | |
//this would be equivalent to the above, but MDN discourages the use of setPrototypeOf | |
// Object.setPrototypeOf(aux.data, constructorFunc.prototype); | |
// return aux.data; | |
} | |
} | |
//------------------------------------ | |
class Account{ | |
constructor(id, owned, debt){ | |
this.id = id; | |
this.owned = owned; | |
this.debt = debt; | |
} | |
getState(){ | |
return this.owned - this.debt; | |
} | |
} | |
//----------------------------------- | |
let p1 = new Account("12abc", 25, 5); | |
let st = TypedSerializer.serialize(p1); | |
console.log("serialized: " + st); | |
let p2 = TypedSerializer.deserialize(st); | |
console.log("instanceof Account? " + (p2 instanceof Account).toString()); | |
console.log("state: " + p2.getState()); | |
console.log(JSON.stringify(p2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment