我将一个名为 session 的对象存储到我的 localStorage 中,以便在浏览器刷新后进一步使用。但我有很多与之相关的函数,例如 session.getUserCount()、session.getPeerIds() 等。我正在使用 .toString() 将其存储到本地存储中,借助此功能,我可以检索直接变量,例如 session.id、session.initiator,但所有函数现在都将值返回为 null。
请帮助我以某种好的方式存储所有函数的值。
提前致谢。
最佳答案
您需要在 Session
类中实现内部 data
json 对象、fromJSON
和 toJSON
方法
但是你需要记住,data
对象只能保存number
、string
、null
、数组
和普通对象
class Session {
constructor(id) {
this.data = {
id: id,
createdAt: Date.now(),
userCount: 0,
user: {
name: 'foo',
likeIds: [1, 56]
}
}
}
getUserCount() {
return this.data.userCount;
}
fromJSON(data) {
this.data = data;
}
toJSON() {
return this.data;
}
}
// Usage
var session = new Session(1);
localStorage.abc = JSON.stringify(session);
var restoredSession = new Session();
try {
restoredSession.fromJSON(JSON.parse(localStorage.abc));
} catch (e) {
console.error('JSON parse error');
}
console.log(restoredSession);
关于javascript - 如何存储函数或函数的值并在浏览器刷新后重用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41592660/