gpt4 book ai didi

保存/加载其状态的 JavaScript 对象

转载 作者:行者123 更新时间:2023-11-29 18:25:37 28 4
gpt4 key购买 nike

我想创建一个可以保存和加载其状态(到本地存储)的 Javascript 对象。

这是我使用的基本模式:

var obj = function () {

// private members
//

return {

// public members

load: function () {
this.state = JSON.parse(localStorage.getItem('obj'));

if (this.state === null) {
this.state = {
name: 'foo'
};
}
},

save: function () {
localStorage.setItem('obj', JSON.stringify(this.state));
}
};
}();

// load state
obj.load();
console.log(obj.state.name);

// save state
obj.state.name = 'bar';
obj.save();

但有一件事让我对这种模式感到恼火:我必须通过“state”属性访问对象的持久属性。

我如何重写它以便我可以以更自然的方式使用该对象,例如:

// load state
obj.load();
console.log(obj.name);

// save state
obj.name = 'bar';
obj.save();

这是一个非常简单的“状态”,但解决方案必须适用于具有嵌套对象、数组等的复杂状态对象,因此简单地向我的对象添加一个“名称”属性并不是我想要的。

最佳答案

如果您不关心加载/保存哪些属性,那么您可以简单地将所有属性从 state 复制到 self。例如,在读入 var state 之后(而不是 this.state 因为你不希望 state 成为 的一部分不再是这个): for(x in state) this[x] = state[x];

类似地,您将保存:var state = {}; for(x in this) 状态[x] = this[x]

但是,如果您想要一个预定义的列表,那么我建议:var fields = ['name', 'zip', 'age'];

然后使用for(x in fields) this[x] = state[x]加载和for(x in fields) state[x] = this[x]; 保存。

抱歉有点拼凑,但我希望你能理解我的意思:)

编辑:根据 OP 请求添加完整示例。

使用此技术的完整解决方案示例如下:

var obj = function () {

// private members
//

return {

// public members

load: function () {
var state = JSON.parse(localStorage.getItem('obj'));

if(state == null) state = { name: 'foo' };

for(x in state) this[x] = state[x];
},

save: function ()
{
var state = {};

// check if it's a function. This version taken from underscorejs
var isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};

for(x in this)
{
if(isFunction(this[x])) continue; // skip functions

state[x] = this[x];
}

localStorage.setItem('obj', JSON.stringify(state));
}
};
};

关于保存/加载其状态的 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13750805/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com