使用打字稿从本地存储中检索后,如何还原对象的原型? [英] How do I restore an object's prototype after retrieving from local storage using typescript?

查看:69
本文介绍了使用打字稿从本地存储中检索后,如何还原对象的原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在原型上有一个带有getTotal()方法的打字稿类.

I have a typescript class with a getTotal() method on the prototype.

class Score {
    roundOne: any;
    roundTwo: any;
    roundThree: any;
    roundFour: any;
    roundFive: any;
    roundSix: any;
    roundSeven: any;
    getTotal() {
      let total = 0;
      if(!isNaN(parseInt(this.roundOne))) total+=parseInt(this.roundOne);
      if(!isNaN(parseInt(this.roundTwo))) total+=parseInt(this.roundTwo);
      if(!isNaN(parseInt(this.roundThree))) total+=parseInt(this.roundThree);
      if(!isNaN(parseInt(this.roundFour))) total+=parseInt(this.roundFour);
      if(!isNaN(parseInt(this.roundFive))) total+=parseInt(this.roundFive);
      if(!isNaN(parseInt(this.roundSix))) total+=parseInt(this.roundSix);
      if(!isNaN(parseInt(this.roundSeven))) total+=parseInt(this.roundSeven);

      return total;
    }
}

该方法可以满足我的需要,直到将"Score"的实例保存到localStorage并尝试检索它为止.原型已从对象中剥离,因此我不再有权访问getTotal()方法.除了重组代码之外,当我从localStorage检索对象时,是否还有任何方法可以将对象重新附加或指向它们的原型?类似于以下内容:

The method works for my needs until I save an instance of 'Score' to localStorage and try to retrieve it. The prototype is stripped from the object so I no longer have access to the getTotal() method. Aside from restructuring my code, is there any way to reattach or point the objects to their prototype when I retrieve them from localStorage? Something along the lines of:

let scores = JSON.parse(localStorage.getItem('scores'));

scores.forEach(function(score){
  // reattach or point to prototype here
})

推荐答案

解析json不会导致类的实例,而是具有包含相同属性的简单js对象.

Parsing a json doesn't result in instance of classes but with simple js objects which contain the same properties.

您(至少)可以通过两种方式解决此问题:
(1)添加一个可以处理此状态对象的构造函数:

You have (at least) two ways to solve this:
(1) Add a constructor which can handle this state object:

class Score {
    roundOne: any;
    roundTwo: any;
    ...

    constructor(state: Score) {
        this.roundOne = state.roundOne;
        this.roundTwo = state.roundTwo;
        ...
    }

    getTotal() {
        ...
    }
}

let scores = (JSON.parse(localStorage.getItem('scores')) as Score[])
    .map(score => new Score(score));

请注意,即使我对状态对象使用类型Score,情况并非如此,但它们只是

Notice that even though I use the type Score for the state objects it's not really the case, they just share the same structure (minus the method). You can make an interface for that as well:

interface State {
    roundOne: any;
    roundTwo: any;
    ...
}

(2)使用 Object.assign :

let scores = (JSON.parse(localStorage.getItem('scores')) as Score[])
    .map(score => Object.assign(new Score(), score));

这篇关于使用打字稿从本地存储中检索后,如何还原对象的原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆