原型模式
创建基类的时候,简单差异化的属性放在构造函数中,消耗资源相同的功能放在基类原型中.
-
图表示例
代码示例
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>
-
效果