【发布时间】: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
})
【问题讨论】:
-
不确定它是否完全重复,但这个问题可能会帮助您解决问题:stackoverflow.com/questions/5873624/…
标签: javascript angular typescript