The requirement is simple. Here's a class...
class myobj {
constructor(var1, var2) {
this.var1 = var1;
this.var2 = var2;
}
addThemUp() {
return this.var1 + this.var2;
}
}
Now I make one of these...
var myInstance = new MyObj(3, 7);
Lovely. But now I need to serialize this so that I can save it and load it up later. Something like...
serialise(myInstance);
// Save to a file
// ... do some other stuff ...
// load from file
myInstance = unserialise(fileData);
// - or -
unserialise(fileData, myInstace);
// etc...
How? I don't care what form the representation takes as it will be loaded by the same page. If values-only are saved, a generic way of loading them back into an object would be fine because the same page has the class 'template' to find the definitions for the functions.
The object is large and changing, so manually copying the values from JSON in order to preserve the functions wouldn't be practically maintainable. But a solution that could do that with any number and typeof variables would be useful.
I've also got to stick to vanilla, single-file javascript, albeit in modern browsers.
TL;DR: How can I serialise and unserialise an object without losing the functions?
You can use JSON.stringify
, but be aware that it only serialize properties, not methods. So to unserialize an object, just create a dummy instance and use Object.assign
to update the properties using the retrieved object:
function serialize(instance) {
var str = JSON.stringify(instance);
// save str or whatever
}
function unserialize(str, theClass) {
var instance = new theClass(); // NOTE: if your constructor checks for unpassed arguments, then just pass dummy ones to prevent throwing an error
var serializedObject = JSON.parse(str);
Object.assign(instance, serializedObject);
return instance;
}
Example:
function serialize(obj) {
var str = JSON.stringify(obj);
return str;
}
function unserialize(str, theClass) {
var instance = new theClass();
var serializedObject = JSON.parse(str);
Object.assign(instance, serializedObject);
return instance;
}
// TEST CLASS
class TestClass {
constructor(a, b) {
this.a = a;
this.b = b;
}
sum() {
return this.a + this.b;
}
}
// USAGE
var instance = new TestClass(5, 7);
var str = serialize(instance);
var retrievedInstance = unserialize(str, TestClass);
console.log(retrievedInstance.sum());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With