There is a new keyword 'class' in ES6 (ECMAScript 6), and my class is this way:
class MyClass {
constructor() {
this.MyProperty = 0;
}
}
var obj = new MyClass();
console.log(obj);
//result:
//MyClass {MyProperty:0}
var str = JSON.stringify(obj);
console.log(str);
//result:
//"{MyProperty:0}"
The matter is 'str' obtained by using JSON.stringify doesn't contain a class name and thus JSON.parse (or other utils) won't be able to unserialise back to the 'obj' object. After using JSON.parse on 'str', the result is no longer instance of MyClass class.
var objFromStr = JSON.parse(str);
console.log(objFromStr);
//result:
//{MyProperty:0}
How to serialise an instance to string and unserialise back to instance in ES6? If JSON.stringify/JSON.parse don't work, any good libraries for using in NodeJS?