【发布时间】:2016-11-28 23:38:29
【问题描述】:
我想创建一个像数组一样工作的对象集合。前段时间,我发了this question,在帮助我的人的帮助下,我想出了以下解决方案:
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.Collections 设置一个全局container 不是解决方案。这是一个示例,我需要它来处理比 render() 函数更复杂的过程。
任何人都知道如何使数组能够访问它所属的父类?
如果解决方案可以是JSON.stringifyed 并被视为服务器端的数组,那也很好,尽管这不是这个问题的主要问题。现在,如果我为数组设置一个属性,它在服务器端被视为带有size > 0 的对象。
谢谢!
【问题讨论】:
标签: javascript arrays collections parent children