我有一个 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/