Last active
September 6, 2016 16:04
-
-
Save asvny/5c10335ce94d5446ff0f680704fc64ce to your computer and use it in GitHub Desktop.
Object function serialize and deserialize
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
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