Using JSON.stringify on custom class

First, you are not defining a class.

It’s just an object, with a property whose value is a function (All its member functions defined in constructor will be copied when create a new instance, that’s why I say it’s not a class.)

Which will be stripped off when using JSON.stringify.

Consider you are using node.js which is using V8, the best way is to define a real class, and play a little magic with __proto__. Which will work fine no matter how many property you used in your class (as long as every property is using primitive data types.)

Here is an example:

function MyClass(){
  this._attr = "foo";
}
MyClass.prototype = {
  getAttr: function(){
    return this._attr;
  }
};
var myClass = new MyClass();
var json = JSON.stringify(myClass);

var newMyClass = JSON.parse(json);
newMyClass.__proto__ = MyClass.prototype;

console.log(newMyClass instanceof MyClass, newMyClass.getAttr());

which will output:

true "foo"

Leave a Comment