Javascript-具有公共父属性的对象的集合
Javascript - Collection of objects with parent properties in common
我想创建一个像数组一样工作的对象集合。不久前,我提出了这个问题,在帮助我的人的帮助下,我想出了以下解决方案:
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.stringify
ed,并在服务器端被视为一个阵列,那也很棒,尽管这不是这个问题的主要问题。现在,如果我为数组设置了一个属性,它将被视为服务器端具有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('.......')
}
但是这个版本需要有方法参数。
相关文章:
- 为什么我可以在Array属性对象中找到Javascript Array for Each方法
- 使用onclick调用属性对象函数
- 嵌套为..in 循环,列出多维对象的属性(对象)
- 动态属性对象 - JSON
- 在不使用隔离范围angularjs自定义指令的情况下获取属性对象
- 通过属性传递属性/对象.Javascript
- Javascript:属性/对象的类型
- 访问JSON中的属性(对象)
- 属性对象Javascript不是用Jquery Deferred设置的
- 无法读取属性'#<对象>'未定义的获取错误
- Twitter中多属性对象的子字符串匹配
- 无法设置'data'属性'对象'标记.(只IE8)
- 更新数据属性对象属性值
- 将属性对象的选定对象从原型推入数组
- 将单个属性对象字面量的数组转换为仅包含其值的数组的最佳方法
- 寻找一种更简单的方法来检查是否多个属性&对象中的方法是未定义的
- 主干模型:带有get方法的空属性,但在属性对象中
- 如何赋值给"text"someText"属性对象在动能js
- Angularjs的数据绑定与数据属性对象
- 如何将一个嵌套的javascript对象转换为只有一级属性对象