Deserializing JavaScript object instance

前端 未结 5 1220
悲哀的现实
悲哀的现实 2021-01-23 11:56

I am working on an app that heavily uses JavaScript. I am attempting to include some object-oriented practices. In this attempt, I have created a basic class like such:

5条回答
  •  醉梦人生
    2021-01-23 12:22

    Disclaimer

    Not a full time time J.S. Developer, answer may have some minor bugs:

    Long Boring Explanation

    As mentioned by @JAAulde, your object cannot be serialized into JSON, because has functions, the technique that you are using doesn't allow it.

    Many people forget or ignore that the objects that are used in an application, may not be exactly the same as saved / restored from storage.

    Short & quick Answer

    Since you already encapsulate the data members of your object into a single field, you may want to try something like this:

    // create J.S. object from prototype
    Item item = new Item();
    
    // assign values as you app. logic requires
    item.data.name = "John Doe";
    item.data.description = "Cool developer, office ladies, love him";
    
    // encoded item into a JSON style string, not stored yet
    var encodedItem = JSON.stringify(item.data)
    
    // store string as a JSON string
    window.localStorage.setItem("itemKey", encodedItem);
    
    // do several stuff
    
    // recover item from storage as JSON encoded string
    var encodedItem = window.localStorage.getItem("itemKey");
    
    // transform into J.S. object
    item.data = JSON.parse(encodedItem);
    
    // do other stuff
    

    Cheers.

提交回复
热议问题