重建一个JSON序列化的对象

6
在我的Web应用程序中,我使用JSON.stringify()(按此处所述)将对象序列化以进行存储。这很好,我可以轻松地从JSON字符串重新创建对象,但我会丢失所有对象的方法。有没有简单的方法将这些方法重新添加到对象中,可能涉及原型,这是我不太熟悉的东西?或者这只���我自己创建一个复杂函数的情况?
编辑:理想情况下,我希望找到像这样的东西:
Object.inheritMethods(AnotherObject);

3
可能是Best way to serialize/unserialize objects in javascript?的重复问题。 - Felix Kling
我想那里的解决方案可能适用于我,需要做一些修改。但我希望更像是 Object.inheritMethods(Object2) 这样的东西 - 我将在原始帖子中澄清这一点。 - Jim
1
在支持的浏览器中,您可以使用 Object.create:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create - Felix Kling
看起来很有前途,我现在会试着玩一下。 - Jim
那个完美地运行了,一旦我修复了其他的错误 :) 如果你想将它提交为答案,我会接受它。 - Jim
2个回答

2
调用JSON.parse后,一旦获得对象,你有很多选择。以下是一些示例。
  1. Mixin

    There are many techniques for doing this, which this article describes nicely. However, here's a simple example that doesn't require any new language features. Remember that an object is essentially just a map, so JS makes it easy to add additional properties to an object.

    var stuffToAdd = function() {
        this.name = "Me";        
    
        this.func1 = function() {
            print(this.name);
        }
    
        this.func2 = function() {
            print("Hello again");
        }
    }
    
    var obj = JSON.parse("{}");
    stuffToAdd.call(obj);
    
  2. Prototypical

    Use the Object.create method that Felix mentioned. Since this is only offered in ES5, you may want to use a shim to guarantee its availability.


0
旧问题,但我今天在搜索那个问题时找到了它。 我已经在其他地方找到了一个最新的解决方案(ES6):
Object.assign(new myclass(), jsonString);

需要注意的是,这仅适用于没有构造函数参数或具有无副作用构造函数的类。 - aeskreis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接