[英]How do I restore an object's prototype after retrieving from local storage using typescript?
I have a typescript class with a getTotal() method on the 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;
}
}
The method works for my needs until I save an instance of 'Score' to localStorage and try to retrieve it. 该方法可以满足我的需求,直到将“ Score”的实例保存到localStorage并尝试检索它为止。 The prototype is stripped from the object so I no longer have access to the getTotal() method. 原型已从对象中剥离,因此我不再有权使用getTotal()方法。 Aside from restructuring my code, is there any way to reattach or point the objects to their prototype when I retrieve them from localStorage? 除了重组代码之外,当我从localStorage检索对象时,是否还有任何方法可以将对象重新附加或指向它们的原型? Something along the lines of: 类似于以下内容:
let scores = JSON.parse(localStorage.getItem('scores'));
scores.forEach(function(score){
// reattach or point to prototype here
})
Parsing a json doesn't result in instance of classes but with simple js objects which contain the same properties. 解析json不会导致类的实例,但是会导致包含相同属性的简单js对象。
You have (at least) two ways to solve this: 您有(至少)两种方法可以解决此问题:
(1) Add a constructor which can handle this state object: (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));
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). 请注意,即使我对状态对象使用了Score
类型,但实际情况并非如此,它们只是共享相同的结构 (减去方法)。 You can make an interface for that as well: 您也可以为此创建一个接口:
interface State {
roundOne: any;
roundTwo: any;
...
}
(2) Use Object.assign : (2)使用Object.assign :
let scores = (JSON.parse(localStorage.getItem('scores')) as Score[])
.map(score => Object.assign(new Score(), score));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.