Skip to content

Instantly share code, notes, and snippets.

@oprearocks
Last active May 26, 2016 10:45
Show Gist options
  • Save oprearocks/ee03109f6f242f2d51b9db267d21c12d to your computer and use it in GitHub Desktop.
Save oprearocks/ee03109f6f242f2d51b9db267d21c12d to your computer and use it in GitHub Desktop.
Object method serialisation while keeping the `this` reference intact
'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