14.第三篇:组合模式

本文摘自 《JavaScript 设计模式》张容铭 著 版权归原作者所有

var News = function(){
  // 子组件容器
  this.children = [];
  // 当前组件元素
  this.element = null;
}
News.prototype = {
  init:function(){
    throw new Error('请重启你的方法');
  },
  add:function(){
    throw new Error('请重启你的方法');
  },
  getElement:function(){
    throw new Error('请重启你的方法');
  }
}
// 容器类构造函数
var Container = function(id,parent){
  // 构造函数继承父类
  News.call(this);
  // 模块id
  this.id = id;
  // 模块父容器
  this.parent = parent;
  // 构建方法
  this.init();
}
// 寄生式继承父类原型方法
inhritprototype(Container,News);
// 构建方法
Container.prototype.init = function(){
  this.element = document.createElement('ul');
  this.element.id = this.id;
  this.element.className = 'new-container';
};
// 添加子元素方法
Container.prototype.getElement = function(child){
  // 在子元素容器中插入子元素
  this.children.push(child);
  // 插入当前组件元素树种
  this.element.appendChild(child.getElement());
  return this;
}
// 获取当前元素方法
Container.prototype.getElement= function(){
  return this.element;
}
// 显示方法
Container.[prototype.show = function(){
  this.parent.appendChild(this.element);
}

var Item = function(classname){
  News.call(this);
  this.classname = classname || '';
  this.init();
}
inheritPrototype(Item,News);
Item.prptotype.init = function(){
  this.element = document.createElement('li');
  this.element.className = this.classname;
}
Item.prototype.add = function(child){
  this.children.push(child);
  this.element.appendChild(child.getElement());
  return this;
}
Item.prototype.getElement = function(){
  return this.element;
}
var NewsGroup = function(classname)(){
  News.call(this);
  this,classname = classname || '';
  this.init();
}
inheriPrototype(NewsGroup,Mews);
NewsGroup.prototype.init = function(){
  this.element = document.createElement('div');
  this.element.className = this.classname;
}
NewsGroup.prtotype.add = function(child){
  this.children.push(child);
  this,element.appenChild(child.getElement());
  return this;
}
NewsGroup.prototype.getElment = function(){
  return this.element;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文摘自 《JavaScript 设计模式》张容铭 著 版权归原作者所有 外观模式 在对页面dom绑定原生点击事件...
    爱吃鱼的肥兔子阅读 1,040评论 0 0
  • 闺蜜,就是只要你需要,她/他便踏遍千山万水来相寻。 上海迪士尼之行,说走就走,带上了期待、抛弃了浮躁,前行的种种阻...
    扉页汤汤阅读 1,755评论 0 0
  • 今天看她的简介,是一个女权主义者,没有兴趣,但是看了下她的句子,还是挺有意思的。 我厌倦了贞洁又郁闷的日子,又没有...
    juan目的导向阅读 4,090评论 0 0
  • 紫薯饭是真的好好吃,甜甜的 估计我会有几天暂时不想吃酱牛肉了,一样食物不能连续吃几天,真的会失去口感的 今天是带饭...
    Sunnyygirl阅读 1,066评论 0 0
  • 现在最热门的技术,应该属区块链项目应用吧!这么火热的区块链你都知道是怎么分类的吗?今天小编给大家讲讲区块链项目的几...
    迷恋薰衣草阅读 1,410评论 0 0