1

我考虑使用保存对象JSON.stringify,然后再次加载它们。“字符串化”当然效果很好,但是我不确定如何设置对象的原型/类。

4

1 回答 1

1

您可以使用.toJSON和 reviver 回调来实现此目的。

这是方案:

function Person() {
    this.name = "name";
    this.age = "age";
}

Person.prototype.toJSON = function() {
            //Define this for other classes as well
    return {__class__: "Person", name: this.name, age: this.age};
};

function reviver( key, value ) {
        if( typeof value == "object" && value.__class__ ) {
            var ret = new window[value.__class__];
            for( var k in value ) {
                if( k === "__class__" ) continue;
                ret[k] = value[k];
            }
            return ret;
        }
        return value;
}

var a = new Person(),
    b = new Person();

var json = JSON.stringify( [a,b] );

var decoded = JSON.parse( json, reviver);

console.log( decoded ); //[Person, Person] I.E. array of Person instances instead of plain objects

在这个简化的方案中,类必须是全局的。

于 2013-01-11T21:31:34.147 回答