javascript - 使用 typescript 从本地存储检索后如何恢复对象的原型(prototype)?

标签 javascript angular typescript

我有一个 typescript 类,原型(prototype)上有一个 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 并尝试检索它之前,该方法可以满足我的需要。原型(prototype)已从对象中剥离,因此我无法再访问 getTotal() 方法。除了重构我的代码之外,当我从 localStorage 检索对象时,是否有任何方法可以将对象重新附加或指向它们的原型(prototype)?类似的东西:

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

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

最佳答案

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

关于javascript - 使用 typescript 从本地存储检索后如何恢复对象的原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42682629/

相关文章:

javascript - 影子 DOM 中的 JQuery 选择元素

javascript - 如果没有值,如何显示没有芯片的区域

javascript - Angular:如何从单选按钮组获取数据并将其作为参数传递给方法?

typescript - Typescript 中的装饰器(注释)是如何编译的?

Angular:我将如何链接 Mat-paginator 的 pageSize 来呈现该数量的项目?

javascript - 在 Selenium RC 的 head 标签内运行 javascript

javascript - 如何使用jquery下载文件?

forms - 如何在测试 Angular 2 react 形式时使用 setValue 和 patchValue

typescript - 使用逻辑赋值时如何保持类型保护缩小?

java - Rhino 报告丢失 : after property id