Javascript-具有公共父属性的对象的集合

Javascript - Collection of objects with parent properties in common

本文关键字:属性 对象 集合 Javascript-      更新时间:2023-09-26

我想创建一个像数组一样工作的对象集合。不久前,我提出了这个问题,在帮助我的人的帮助下,我想出了以下解决方案:

Newobj.Collection = function(){
    Array.apply(this);
    for(var i = 0; i < arguments.length; i++){
        for(var j = 0; j < arguments[i].length; j++){
            this.push(arguments[i][j]);
        }
    }
    return this
}
Newobj.Collection.prototype = Object.create(Array.prototype);
Newobj.Collection.prototype.push = function(o){
    Array.prototype.push.call(this, new Newobj.Element(o));
}

但是,这会使子对象与父对象没有连接。例如,假设这个集合有一个render()函数,它使它的子级可以在页面上打印一些HTML。好吧,我想说一些类似的话:

Newobj.Collection.html_container = '#cont';
Newobj.Collection.render = function(){
    $.each(this, function(i, el){
        el.render()
    })
}
Newobj.Element.render = function(){
    $(parent.html_container).html('.......')
}

它应该能够在一个页面中设置不同的集合,因此为所有Newobj.Collection创建全局container不是一个解决方案。这是一个例子,对于比render()函数更复杂的过程,我需要它。

任何人都知道如何制作一个数组来访问它所属的父类吗?

如果解决方案可以是JSON.stringifyed,并在服务器端被视为一个阵列,那也很棒,尽管这不是这个问题的主要问题。现在,如果我为数组设置了一个属性,它将被视为服务器端具有size > 0的对象

谢谢!

在元素中创建对集合的引用

Newobj.Collection.prototype.push = function(o){
  Array.prototype.push.call(this, new Newobj.Element(o,this));
}
//element constructor gets as second paramater instance of collection
Newobj.Element=function(o,collection){
  //this.parent in every element is collection reference
  this.parent=collection;
}

Newobj.Element.prototype.render = function(){
   $(this.parent.html_container).html('.......')
}

或元素选项中没有参考:

Newobj.Collection.render = function(){
  var parent=this;
  $.each(this, function(i, el){
    el.render(parent.html_container)
  })
}
Newobj.Element.render = function(html_container){
  $(html_container).html('.......')
}

但是这个版本需要有方法参数。