類:
降低維護成本、使代碼高度復用、擴充方便靈活
OOP 面向物件開發
核心:封裝
類->工廠->物件
ES6中的類
//車類 class Car{ //建構式 constructor(){ console.log("開始造車"); } } //實體化,類->物件 let c=new Car();

建構式的寫法有點類似于簡潔表示法:
//建構式的寫法類似簡潔表示法 let obj={ //普通寫法 fn:function(){ }, //簡潔表示法 fn2(){ } }
//車類 class Car{ //建構式 constructor(wheel,color,length,width){//接收引數 //給屬性賦值,this指向當前實體化的結果 this.wheel=wheel; this.color=color; this.length=length; this.width=width; this.speed=0; } //方法 speedUp(){ this.speed+=1; } } //實體化,類->物件 let c=new Car(3,"#abcdef",20,40); console.log(c); c.speedUp();//呼叫實體(物件)的方法 console.log(c.speed);//獲取實體(物件)的屬性

不同實體之間是相互獨立的
//車類 class Car{ //建構式 constructor(wheel,color,length,width){//接收引數 //給屬性賦值,this指向當前實體化的結果 this.wheel=wheel; this.color=color; this.length=length; this.width=width; this.speed=0; } //方法 speedUp(){ this.speed+=1; } } //實體化,類->物件 let c1=new Car(3,"#abcdef",20,40); let c2=new Car(4,"pink",10,40); console.log(c1,c2);

音樂播放器類實體
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ES6 class</title>
</head>
<style>
</style>
<body>
<div id="app"></div>
<script>
//模擬一個播放器類
class AudioPlayer{
constructor(container){//接收引數
this.container=document.querySelector(container);
this.songsList=[];
this.dom=null;
this.audio=new Audio();
this.status=0;//標記播放器的狀態
this.getSongs();//獲取歌單串列
this.createElement();//創建DOM
this.bindEvent();//系結事件
this.render();//渲染到頁面
}
getSongs(){
//模擬ajax請求拿資料
this.songsList=[
{
songName:"name1",
songCover:"cover1",//封面
songSinger:"singer1",//歌手
songUrl:"url1"//資源地址
},
{
songName:"name2",
songCover:"cover2",//封面
songSinger:"singer2",//歌手
songUrl:"url2"//資源地址
}
];
}
createElement(){
const div=document.createElement("div");
div.innerHTML=`
<div >播放按鈕</div>
<div>進度條</div>
`;
this.dom=div;
}
bindEvent(){
this.dom.querySelector(".btn").addEventListener("click",()=>{
console.log("開始播放");
})
}
render(){
this.container.appendChild(this.dom);
}
}
new AudioPlayer("#app");
</script>
</body>
</html>

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/139484.html
標籤:JavaScript
上一篇:ES6 Promise --回呼與Promise的對比、信任問題、錯誤處理、Promise的狀態、以及Promise物件的常用方法
下一篇:Ajax和Http的常用狀態碼
