Last active
May 26, 2016 10:45
-
-
Save oprearocks/ee03109f6f242f2d51b9db267d21c12d to your computer and use it in GitHub Desktop.
Object method serialisation while keeping the `this` reference intact
This file contains 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
'use strict'; | |
let person = { | |
name: 'Adrian', | |
age: 28, | |
sayName: function() { | |
console.log(`My name is ${this.name}`); | |
console.log(this); // this should log out our `person` object | |
} | |
}; | |
let replacer = (k, v) => { | |
if (typeof v === 'function') { | |
return v.toString(); | |
} | |
return v; | |
} | |
let strPerson = JSON.stringify(person, replacer, 2); | |
console.log(strPerson); | |
let reviver = (k, v) => { | |
if (typeof v === 'string' && v.indexOf('function ') === 0) { | |
return eval(`(${v})`); | |
// return Function(`(${v}).call(this)`); | |
} | |
return v; | |
} | |
let objPerson = JSON.parse(strPerson, reviver); | |
console.log(objPerson); | |
objPerson.sayName(); // should also print the person clone(objPerson) as being the `this` reference | |
objPerson === person; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment