Deserializing JavaScript object instance

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

    I know this question is answered already, however I stumbled upon this by accident and wanted to share a solution to this problem, if anyone is interested.

    instead of doing this:

    var item = window.localStorage.getItem("itemKey");
    item = JSON.parse(item);
    item.save();
    

    do something like this:

    // get serialized JSON
    var itemData = window.localStorage.getItem("itemKey");
    //instantiate new Item object
    var item = new Item();
    // extend item with data
    $.extend(item, JSON.parse(itemData));
    
    // this should now work
    item.save();
    

    this will work so long as the function you are wanting to call (ie, save()) is prototypal and not an instance method (often times the case, and is indeed the case in the OP's original question.

    the $.extend method is a utility method of jquery, but it is trivial to roll your own.

提交回复
热议问题