HTML5 LocalStorage 中的自定义对象类?

Dyl*_*lan 3 html oop local-storage

我正在尝试 HTML5 LocalStorage。

在示例中,我只看到简单的 JSON 数据对象,但我添加了一些自定义数据对象类,其中添加了各种方法(如 addChild、cleanup 等)。

是否可以将这些自定义对象的实例直接存储在 LocalStorage 中,或者我是否理解 LocalStorage 的整个概念完全错误?

Exp*_*lls 5

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());
Run Code Online (Sandbox Code Playgroud)