美文网首页
14.第三篇:组合模式

14.第三篇:组合模式

作者: 爱吃鱼的肥兔子 | 来源:发表于2018-12-14 11:51 被阅读0次

    本文摘自 《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;
    }
    

    相关文章

      网友评论

          本文标题:14.第三篇:组合模式

          本文链接:https://www.haomeiwen.com/subject/oksuhqtx.html