HTML5 LocalStorage中的自定义对象类? [英] Custom object classes in HTML5 LocalStorage?
问题描述
我正在尝试HTML5 LocalStorage.
I'm trying out HTML5 LocalStorage.
在示例中,我仅看到简单的JSON数据对象,但是我有一些自定义数据对象类,其中添加了各种方法(例如addChild,cleanup等).
In the examples I only see simple JSON data-objects, but I have some custom data-object classes with various methods added (like addChild, cleanup, etc).
是否可以将这些 custom 对象的实例直接存储在LocalStorage中,或者我是否完全理解LocalStorage的整个概念呢?
Is it possible to store instances of these custom objects directly in LocalStorage, or do I understand the whole concept of LocalStorage totally wrong then?
推荐答案
localStorage
仅可以存储字符串,因此,您尝试存储在localStorage
中的任何内容都将首先序列化为字符串.因此,将定义存储在localStorage
中只是数据.您可以创建一种从序列化数据生成自定义对象实例的方法:
localStorage
can only store strings, so anything you try to store in localStorage
will be serialized to a string first. As such it doesn't make sense to store definitions in localStorage
, just data. You can create a method that generates a custom object instance from serialized data:
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());
这篇关于HTML5 LocalStorage中的自定义对象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!