简体   繁体   English

重建以JSON序列化的对象

[英]Rebuilding an object serialized in JSON

In my web app, I'm serializing objects for storage using JSON.stringify() as described here . 在我的Web应用程序中,我使用JSON.stringify()序列化对象以进行存储, 如此处所述 This is great, and I can easily re-create the objects from the JSON strings, but I lose all of the objects' methods. 这很棒,我可以轻松地从JSON字符串重新创建对象,但是我丢失了所有对象的方法。 Is there a simple way to add these methods back to the objects that I'm overlooking - perhaps involving prototyping, something I'm not overly familiar with? 有没有一种简单的方法将这些方法添加回我正在忽略的对象 - 可能涉及原型设计,我不太熟悉的东西?

Or is it just a case of creating an elaborate function of my own for doing this? 或者只是为了这样做而创建我自己的精细功能?

Edit: Ideally, I'm looking for something like: 编辑:理想情况下,我正在寻找类似的东西:

Object.inheritMethods(AnotherObject);

Once you have your object after calling JSON.parse, you have many options. 在调用JSON.parse后获得对象后,您有很多选择。 Here's a few examples. 这是一些例子。

  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. 请记住,对象本质上只是一个映射,因此JS可以轻松地向对象添加其他属性。

     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. 使用Felix提到的Object.create方法。 Since this is only offered in ES5, you may want to use a shim to guarantee its availability. 由于这仅在ES5中提供,因此您可能需要使用垫片来保证其可用性。

Old question, but I found it when searching for that problem today. 老问题,但我今天在搜索这个问题时找到了它。 I've found a solution elsewhere and uptodate (ES6): 我在其他地方找到了一个解决方案,并且已经找到了解决方案(ES6):

Object.assign(new myclass(), jsonString); Object.assign(new myclass(),jsonString);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM