在javascript中,類是一種用戶定義類型,也稱類類型,是一個具有相同屬性和行為的群體的集合;從es6開始,可通過創(chuàng)建class關(guān)鍵字來定義一個類的模板,例“class 類名{}”。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
什么是類
在面向?qū)ο缶幊讨校悾╟lass)是對象(object)的模板,定義了同一組對象(又稱"實(shí)例")共有的屬性和方法。類是一種用戶定義的引用數(shù)據(jù)類型,也稱類類型。
我們可以理解類是一個具有相同屬性和行為的群體的集合。
JS 中的類
在ES5之前,JS中要表達(dá)一個類,要用一種叫做prototype-based
的語法風(fēng)格
function 士兵(id,hp){ this.id = id this.hp = hp } 士兵.prototype = { constructor:士兵() walk:function(){ } , Shooting:function(){ } , }
在es6中,首次引入了類的概念,通過創(chuàng)建class關(guān)鍵字來定義一個類的模板。
1、在js中實(shí)現(xiàn)創(chuàng)建一個Class
class Number{ }
2、實(shí)現(xiàn)Class的構(gòu)造方法、實(shí)例屬性和實(shí)例方法
//構(gòu)造方法 class Number{ //實(shí)例屬性 constructor(id,age){ //this指向當(dāng)前事件 this.id=id; this.age=age; } //實(shí)例方法 num(){ console.log("hh"); } } //實(shí)例化對象 var n1=new Number("1","2"); n1.num(1); console.log(n1.id); console.log(n1.age); var n2=new Number("3","4"); n2.num(2); console.log(n2.id); console.log(n2.age);
效果展示:
hh 1 2 hh 3 4
3、Class的靜態(tài)屬性和靜態(tài)方法
//構(gòu)造方法 class Number{ //靜態(tài)屬性調(diào)用一個方法 static ppp=1; //實(shí)例屬性 constructor(id,age){ //this指向當(dāng)前事件 this.id=id; this.age=age; console.log(Number.ppp) } //實(shí)例方法 num(){ console.log("hh"); }} //實(shí)例化對象 var n1=new Number("1","2"); n1.num(1); console.log(n1.id); console.log(n1.age); var n2=new Number("3","4"); n2.num(2); console.log(n2.id); console.log(n2.age);
效果展示:
1 hh 1 2 1 hh 3 4
4、類的繼承
//父類 class Father{ //構(gòu)造方法不能被繼承 constructor(){ console.log("我是父親"); this.name="father" } } //子類 class Son extend Father{ //執(zhí)行子類構(gòu)造方法之前必須先執(zhí)行父類構(gòu)造方法 constructor(){ super();//執(zhí)行父類構(gòu)造方法 console.log("我是兒子") } } var son=new Son; console.log(son.name)
效果展示:
我是父親 我是兒子 father
【推薦學(xué)習(xí):javascript高級教程】