Last active
August 29, 2015 14:08
-
-
Save Shinpeim/ef41d6ee7a6469d06342 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 obj = json.obj; | |
obj.__proto__ = global[klass].prototype; | |
return obj; | |
} | |
}; | |
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(nyanClone.a); // => "a" | |
console.log(nyanClone.b); // => "b" | |
console.log(nyanClone.nyan()); // => "ab" | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment