本文實(shí)例講述了ES6中定義類和對(duì)象的方法。分享給大家供大家參考,具體如下:
類的基本定義和生成實(shí)例:
// 類的基本定義和生成實(shí)例 class Parent{ //定義一個(gè)類 constructor(name='xiaxaioxian'){ this.name= name; } } // 生成一個(gè)實(shí)例 let g_parent = new Parent(); console.log(g_parent); //{name: "xiaxaioxian"} let v_parent = new Parent('v') // 'v'就是構(gòu)造函數(shù)name屬性 , 覆蓋構(gòu)造函數(shù)的name屬性值 console.log(v_parent); // {name: "v"}
繼承
// 繼承 class Parent{ //定義一個(gè)類 constructor(name='xiaxaioxian'){ this.name= name; } } class Child extends Parent{ } console.log('繼承',new Child()) // 繼承 {name: "xiaxaioxian"}
繼承傳遞參數(shù)
// 繼承傳遞參數(shù) class Parent{ //定義一個(gè)類 constructor(name='xiaxaioxian'){ this.name= name; } } class Child extends Parent{ constructor(name = 'child'){ // 子類重寫name屬性值 super(name); // 子類向父類修改 super一定放第一行 this.type= 'preson'; } } console.log('繼承',new Child('hello')) // 帶參數(shù)覆蓋默認(rèn)值 繼承{name: "hello", type: "preson"}
ES6重新定義的ES5中的訪問(wèn)器屬性
class Parent{ //定義一個(gè)類 constructor(name='xiaxaioxian'){ this.name= name } get longName(){ // 屬性 return 'mk' + this.name } set longName(value){ this.name = value } } let v = new Parent(); console.log('getter',v.longName) // getter mkxiaxaioxian v.longName = 'hello'; console.log('setter',v.longName) // setter mkhello
類的靜態(tài)方法:
class Parent{ //定義一個(gè)類 constructor(name='xiaxaioxian'){ this.name= name } static tell(){ // 靜態(tài)方法:通過(guò)類去調(diào)用,而不是實(shí)例 console.log('tell') } } Parent.tell(); // tell
類的靜態(tài)屬性:
// 靜態(tài)屬性 class Parent{ //定義一個(gè)類 constructor(name='xiaxaioxian'){ this.name= name } static tell(){ // 靜態(tài)方法:通過(guò)類去調(diào)用,而不是實(shí)例 console.log('tell') // tell } } Parent.type = 'test'; // 定義靜態(tài)屬性 console.log('靜態(tài)屬性',Parent.type) // 靜態(tài)屬性 test let v_parent = new Parent(); console.log(v_parent); // {name: "xiaxaioxian"} 沒(méi)有tell方法和type屬性
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運(yùn)行工具:http://tools.jb51.net/code/HtmlJsRun測(cè)試上述代碼運(yùn)行效果。
更多關(guān)于JavaScript相關(guān)內(nèi)容可查看本站專題:《javascript面向?qū)ο笕腴T教程》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com