Using JSON.stringify on custom class

前端 未结 5 2010
执笔经年
执笔经年 2020-12-06 12:51

I\'m trying to store an object in redis, which is an instance of a class, and thus has functions, here\'s an example:

function myClass(){
    this._attr = \"         


        
5条回答
  •  渐次进展
    2020-12-06 13:27

    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"
    

提交回复
热议问题