Created
October 31, 2014 14:30
-
-
Save Shinpeim/6d9d222cee7d7dc0d0b3 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){ | |
json = JSON.parse(string); | |
obj = json.obj; | |
klass = json.klass; | |
obj.prototype = 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(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