类:
降低维护成本、使代码高度复用、扩充方便灵活
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);
音乐播放器类实例
ES6 class//模拟一个播放器类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();//创建DOMthis.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=`播放按钮进度条 `;this.dom=div; } bindEvent(){this.dom.querySelector(".btn").addEventListener("click",()=>{ console.log("开始播放"); }) } render(){this.container.appendChild(this.dom); } }new AudioPlayer("#app");" _ue_custom_node_="true">
Copyright © 2004-2024 Ynicp.com 版权所有 法律顾问:建纬(昆明)律师事务所 昆明市网翼通科技有限公司 滇ICP备08002592号-4