我正在试用 HTML5 LocalStorage。
在示例中,我只看到简单的 JSON 数据对象,但我有一些自定义数据对象 类 添加了各种方法(如 addChild、cleanup 等)。
是否可以将这些自定义对象的实例直接存储在 LocalStorage 中,或者我对 LocalStorage 的整个概念的理解是否完全错误?
最佳答案
localStorage
只能存储字符串,因此您尝试存储在 localStorage
中的任何内容都将首先序列化为字符串。因此,在 localStorage
中存储定义 没有意义,只是数据。您可以创建一个从序列化数据生成自定义对象实例的方法:
function Custom() {}
Custom.prototype.addChild = function () {
console.log(this.x, this.y);
}
// LocalStorage serializes to String first
Custom.prototype.toString = function () {
return JSON.stringify({
"x": this.x,
"y": this.y,
});
};
Custom.unserialize = function (customData) {
customData = JSON.parse(customData);
var custom = new Custom;
custom.x = customData.x;
custom.y = customData.y;
return custom;
}
var custom = new Custom;
custom.x = "foo";
custom.y = "bar";
localStorage.custom = custom;
console.log(Custom.unserialize(localStorage.custom).addChild());
关于html - HTML5 LocalStorage 中的自定义对象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23295160/