Deserializing JavaScript object instance

前端 未结 5 1258
悲哀的现实
悲哀的现实 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:37

    You can only store plain Objects in DOMstorages (cookies, urlparams..., everything that needs [de]serialisation through JSON.stringify/JSON.parse). So what you did when sending the ajax data

    ajaxsend(this.data);
    

    also applies to string serialisation. You can only store the data, not the instance attributes (like prototype, constructor etc.). So use

    savestring(JSON.stringify(item.data));
    

    which is possible because item.data is such a plain Object. And when restoring it, you will only get that plain data Object back. In your case it's easy to reconstruct a Item instance from plain data, because your Items hold their values (only) in a public available property:

    var item = new Item;
    item.data = JSON.parse(getjsonstring());
    

提交回复
热议问题