Created
October 31, 2014 14:43
-
-
Save Shinpeim/b3e5b414ed8d8e651f3b to your computer and use it in GitHub Desktop.
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
(function(global){ | |
Nyan = function(a, b){ | |
this.a = a; | |
this.b = b; | |
}; | |
Nyan.prototype.klass = 'Nyan'; | |
Nyan.prototype.nyan = function(){return this.a + this.b}; | |
global.Nyan = Nyan; // export | |
var serializer = { | |
serialize: function(obj){ | |
if (obj.klass === undefined) { | |
throw new Error("object to be serialized must have 'klass' attribute") | |
} | |
return JSON.stringify({ | |
klass: obj.klass, | |
obj: obj, | |
}); | |
}, | |
deserialize: function(string){ | |
var json = JSON.parse(string); | |
var klass = json.klass; | |
var newObj = new global[klass](); | |
for (var k in json.obj) { | |
newObj[k] = json.obj[k] | |
} | |
return newObj; | |
} | |
}; | |
var nyan = new Nyan('a', 'b'); | |
var serializedNyan = serializer.serialize(nyan); | |
console.log(serializer.serialize(nyan));// => {"klass":"Nyan","obj":{"a":"a","b":"b"}} | |
var nyanClone = serializer.deserialize(serializedNyan); | |
console.log(nyanClone);// => { a: 'a', b: 'b' } | |
console.log(nyan.a); // => "a" | |
console.log(nyan.b); // => "b" | |
console.log(nyan.nyan()); // => "ab" | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment