欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ES6中定義類和對象的方法示例

 更新時間:2019年07月31日 08:45:24   作者:xiaxiaoxian  
這篇文章主要介紹了ES6中定義類和對象的方法,結(jié)合實(shí)例形式分析了ES6中類的定義、繼承、靜態(tài)方法、靜態(tài)屬性等相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了ES6中定義類和對象的方法。分享給大家供大家參考,具體如下:

類的基本定義和生成實(shí)例:

// 類的基本定義和生成實(shí)例
class Parent{ //定義一個類
    constructor(name='xiaxaioxian'){
     this.name= name;
    }
}
// 生成一個實(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{ //定義一個類
    constructor(name='xiaxaioxian'){
     this.name= name;
    }
}
class Child extends Parent{
}
console.log('繼承',new Child()) // 繼承 {name: "xiaxaioxian"}

繼承傳遞參數(shù)

// 繼承傳遞參數(shù)
class Parent{ //定義一個類
    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中的訪問器屬性

class Parent{ //定義一個類
    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{ //定義一個類
   constructor(name='xiaxaioxian'){
    this.name= name
   }
   static tell(){ // 靜態(tài)方法:通過類去調(diào)用,而不是實(shí)例
    console.log('tell')
   }
}
Parent.tell(); // tell

類的靜態(tài)屬性:

// 靜態(tài)屬性
class Parent{ //定義一個類
   constructor(name='xiaxaioxian'){
    this.name= name
   }
   static tell(){ // 靜態(tài)方法:通過類去調(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"} 沒有tell方法和type屬性

感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運(yùn)行工具http://tools.jb51.net/code/HtmlJsRun測試上述代碼運(yùn)行效果。

更多關(guān)于JavaScript相關(guān)內(nèi)容可查看本站專題:《javascript面向?qū)ο笕腴T教程》、《JavaScript錯誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)

希望本文所述對大家JavaScript程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論