【问题标题】:How do I restore an object's prototype after retrieving from local storage using typescript?使用打字稿从本地存储检索后如何恢复对象的原型?
【发布时间】:2017-03-08 21:54:51
【问题描述】:

我有一个 typescript 类,原型上有一个 getTotal() 方法。

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 中检索对象时,是否有任何方法可以将对象重新附加或指向它们的原型?大致如下:

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

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

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

解析 json 不会生成类的实例,而是生成包含相同属性的简单 js 对象。

你有(至少)两种方法来解决这个问题:
(1) 添加一个可以处理这个状态对象的构造函数:

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,但情况并非如此,它们只是 share the same structure(减去方法)。您也可以为此创建一个界面:

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));

【讨论】:

    猜你喜欢
    • 2012-11-06
    • 2017-12-21
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 2013-10-07
    • 1970-01-01
    相关资源
    最近更新 更多