在Javascript(Node.js)中保存/加载复杂的对象结构

时间:2014-09-11 02:32:24

标签: javascript json node.js

我已经用javascript编写了一段时间,但对Node来说还是个新手。我最近进行了一个涉及复杂对象结构的项目,该结构具有多级原型继承和子对象。需要定期保存/加载此结构。用JSON保存和加载是可取的。

问题

是否有一种更优雅的方式来完成保存/加载这些复杂的Javascript对象的任务,而不是我当前的方法(如下所述)?是否有可能以这样的方式设计它,即构造函数可以将自己初始化为好像它们是普通对象而不受所有恢复功能的约束?

我的解决方案

基地'班级' (根据设计,所考虑的所有其他对象都是原型继承的)具有处理“选项”的功能。参数,将所有属性添加到当前对象。所有派生对象必须包含一个options参数作为最后一个参数,并在其构造函数中调用处理函数。

每个对象也必须将它的函数名添加到特定属性中,以便在需要重建对象时可以调用正确的构造函数。

解包函数获取保存的对象JSON,使用JSON.parse创建一个普通对象,然后将该对象作为'选项'对象构造函数的参数。

每个对象都有一个唯一的id并存储在查找表中,因此正在构建的函数可以指向正确的对象,或者在需要时创建它们。

这是一个plunker,它演示了这个想法(显然是以非节点的方式)。

如果你不想装载羽毛球,这里有一段摘录,希望能够提供我想要做的事情的要点:

function BaseClass(name, locale, options){
  if(name) this.name = name;
  if(locale) this.locale = locale;

  // If options are defined, apply them
  this.processOptions(options);

  // create the classList array which keeps track of
  // the object's prototype chain
  this._classList = [arguments.callee.name];

  // Create a unique id for the object and add it to
  // the lookup table
  if(!this.id) this.id = numEntities++;
  lookupTable[this.id] = this;

  if(!this.relations) this.relations = [];

  // other initialization stuff
}

BaseClass.prototype = {
  processOptions: function(options) {
    if(options && !options._processed){
            for(var key in options){
                if(options.hasOwnProperty(key)){
                    this[key] = options[key];
                }
            }
            options._processed = true;
        }
  },
  addNewRelation: function(otherObj){
    this.relations.push(otherObj.id);
  }

  // Other functions and such for the base object
}

function DerivedClassA(name, locale, age, options){
  if(age) this.age = age;

  this.processOptions(options);

  if(options && options.connectedObj){

    // Get the sub object if it already exists
    if(lookupTable[options.subObj.id]){
      this.subObj = lookupTable[options.subObj.id];
    }
    // Otherwise, create it from the options
    else {
      this.subObj = new OtherDerivedClass(options.subObj);
    }
  }
  else {
    // If no options then construct as normal
    this.subObj = new OtherDerivedClass();
  }

  // If something needs to be done before calling the super
  // constructor, It's done here.

  BaseClass.call(this, name, locale, options);
  this._classList.push(arguments.callee.name);

}

DerivedClassA.prototype = Object.create(BaseClass.prototype);

如上所述,这可以完成工作,但我无法帮助,但感觉这可能会好得多。它似乎对继承的课程施加了一些荒谬的限制。以及他们的构造者必须如何表现。它使特定的执行顺序变得至关重要,并要求每个对象都深入参与并了解恢复过程,这远非理想。

0 个答案:

没有答案