Javascript: 反序列化对象和混合方法

Javascript: Deserialize object and mix-in methods

在 Javascript 中,我目前正在使用 localStorage。由于无法放入对象,因此我之前 JSON.stringify-ing 它们。

我正在存储整个游戏状态,一些子对象有方法。

当使用 JSON.parse 读回它们时,方法消失了 - 这绝对有意义。将包含方法的对象存储在浏览器中是愚蠢的。

什么是 "reattach" 对象之前拥有的方法的最佳方式,以便对象可以像以前一样运行?

直接做是不是一个好方法

savedObj.prototype = MyClass.prototype;

我是不是漏掉了什么?

也许你想做这样的事情?

Javascript

function MyClass(state) {
    if (typeof state === 'string') {
        this.state = JSON.parse(state);
    } else {
        this.state = {};
    }

    this.appendChild = function (element) {
        element.appendChild(document.createTextNode(this.toJSON()));
    }
}

MyClass.prototype = {
    log: function () {
        console.log(this.toJSON());

        return this;
    },
    set: function (key, value) {
        this.state[key] = value;

        return this;
    },
    toJSON: function () {
        return JSON.stringify(this.state);
    }
};

var myClass1 = new MyClass();

myClass1.set('somekey', true);
myClass1.log();

localStorage.mySave = myClass1.toJSON();

var myClass2 = new MyClass(localStorage.mySave);

myClass2.log();
myClass2.appendChild(document.body);

jsFiddle