Skip to content

Instantly share code, notes, and snippets.

@ushiboy
Created October 31, 2014 15:25
Show Gist options
  • Save ushiboy/14be7eb9045241a81f45 to your computer and use it in GitHub Desktop.
Save ushiboy/14be7eb9045241a81f45 to your computer and use it in GitHub Desktop.
function Hoge(name) {
this.name = name;
}
Hoge.prototype.greet = function() {
return 'Hello, ' + this.name;
};
Hoge.prototype.toJSON = function() {
var key, ret = { __meta__ : {} };
for (key in this) {
switch (typeof(this[key])) {
case 'string':
case 'number':
case 'boolean':
case 'object':
ret[key] = this[key];
break;
case 'function':
ret.__meta__[key] = this[key].toString();
break;
}
}
return ret;
};
function deserialize(s) {
var d = JSON.parse(s),
f = function() {},
meta = d.__meta__,
k, proto = {};
delete(d['__meta__']);
for (k in meta) {
proto[k] = Function('return ' + meta[k])();
}
f.prototype = proto;
var ins = new f(),
p;
for (p in d) {
ins[p] = d[p];
}
return ins;
}
var hoge = new Hoge('test');
var s = JSON.stringify(hoge);
var ins = deserialize(JSON.stringify(hoge));
console.log(ins.name);
console.log(ins.greet());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment