設計模式(十一)-原型模式

原型模式

創建基類的時候,簡單差異化的屬性放在構造函數中,消耗資源相同的功能放在基類原型中.

  • 圖表示例


    image.png
  • 代碼示例

function Car(name,color,size){
        this.name=name
        this.color=color;
        this.size=size;
}

Car.prototype.make=function(){
    return console.log(`${this.color}的${this.name}車:尺寸${this.size}米`)
}

let c1=new Car('寶馬','白色',2)
let c2=new Car('奔馳','黑色',2)
c1.make()
c2.make()
console.log(c1.make===c2.make) //true

  • 應用場景
    1.tab選項卡
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>tab選項卡</title>
    <style>
        .tab-panel{
            list-style: none;
            display: flex;
            
        }
        li{
            width: 200px;
            height: 200px;
            background: red;
            display: none;
        }
        .active{
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <button class="btn">選項一</button>
        <button class="btn">選項二</button>
        <button class="btn">選項三</button>
        <ul class="tab-panel">
            <li class="active">1</li>
            <li>2</li>
            <li>3</li>
        </ul>
    </div>
    <script>
          function Tab(){

          }
          Tab.prototype.init=function(btn,list){
              this.btns=document.querySelectorAll(btn)
              this.lists=document.querySelectorAll(list)
              this.addEvent()
          }
          Tab.prototype.addEvent=function(){
              this.btns.forEach((btn,index)=>{
                  btn.addEventListener('click',()=>{
                      this.clearClass()
                      this.render(index)
                  })
              })
          }
          Tab.prototype.clearClass=function(){
             this.lists.forEach(list=>{
                list.className=''
             })
          }
          Tab.prototype.render=function(index){
              this.lists[index].className='active'
          }
          let tab=new Tab()
          tab.init('.btn','li')
    </script>
</body>
</html>
  • 效果


    image.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容