Skip to content

Instantly share code, notes, and snippets.

@asvny
Last active September 6, 2016 16:04
Show Gist options
  • Save asvny/5c10335ce94d5446ff0f680704fc64ce to your computer and use it in GitHub Desktop.
Save asvny/5c10335ce94d5446ff0f680704fc64ce to your computer and use it in GitHub Desktop.
Object function serialize and deserialize
let obj = {
id: 14521,
name: 'Annamalai',
notify:function(){
console.log(`Hallo ${this.name} ! Your ID is ${this.id}`)
}
}
//obj.notify();
const change = (key,val) => {
if(typeof val === 'function') {
return val.toString();
}
return val;
}
const stringObj = JSON.stringify(obj,change);
//console.log(stringObj);
const revert = (key,val) => {
if(typeof val === 'string' && val.indexOf('function') !== -1) {
let newFnStr = `(${val}).call(this)`;
return new Function(newFnStr);
}
return val;
}
const parseObj = JSON.parse(stringObj,revert);
console.log(parseObj);
parseObj.notify();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment