Using JSON.stringify on custom class

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

    What you get back grom JSON.stringify() is a String. A string has no methods. You need to eval first that string and then you'll be able to get the original object and its methods.

    var myObj = new myClass();
    var stringObj = JSON.stringify(myObj);
    

    ---- EDIT -----

    //Sorry use this:
    var getBackObj  = JSON.parse(stringObj);
    //Not this
    var getBackObj = eval(stringObj);
    
    console.log(getBackObj.getAttr()); // this should work now
    

提交回复
热议问题