我在原型上有一个带有getTotal()方法的typescript类。
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
})
答案 0 :(得分:2)
解析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));