Using JSON.stringify on custom class

前端 未结 5 1995
执笔经年
执笔经年 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:24

    No, JSON does not store functions (which would be quite inefficient, too). Instead, use a serialisation method and a deserialisation constructor. Example:

    function MyClass(){
        this._attr = "foo";
        this.getAttr = function(){
            return this._attr;
        }
    }
    MyClass.prototype.toJSON() {
        return {attr: this.getAttr()}; // everything that needs to get stored
    };
    MyClass.fromJSON = function(obj) {
        if (typeof obj == "string") obj = JSON.parse(obj);
        var instance = new MyClass;
        instance._attr = obj.attr;
        return instance;
    };
    

提交回复
热议问题