怎么在ES6中定義一個(gè)類和對(duì)象?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

類的基本定義和生成實(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中的訪問器屬性
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)方法:通過類去調(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)方法:通過類去調(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屬性看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。
網(wǎng)頁名稱:怎么在ES6中定義一個(gè)類和對(duì)象-創(chuàng)新互聯(lián)
文章位置:http://www.chinadenli.net/article12/dehjdc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、品牌網(wǎng)站制作、移動(dòng)網(wǎng)站建設(shè)、Google、外貿(mào)網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容