怎么在ES6中定義一個類和對象?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
類的基本定義和生成實例:
// 類的基本定義和生成實例
class Parent{ //定義一個類
constructor(name='xiaxaioxian'){
this.name= name;
}
}
// 生成一個實例
let g_parent = new Parent();
console.log(g_parent); //{name: "xiaxaioxian"}
let v_parent = new Parent('v') // 'v'就是構造函數name屬性 , 覆蓋構造函數的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"}繼承傳遞參數
// 繼承傳遞參數
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')) // 帶參數覆蓋默認值 繼承{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類的靜態方法:
class Parent{ //定義一個類
constructor(name='xiaxaioxian'){
this.name= name
}
static tell(){ // 靜態方法:通過類去調用,而不是實例
console.log('tell')
}
}
Parent.tell(); // tell類的靜態屬性:
// 靜態屬性
class Parent{ //定義一個類
constructor(name='xiaxaioxian'){
this.name= name
}
static tell(){ // 靜態方法:通過類去調用,而不是實例
console.log('tell') // tell
}
}
Parent.type = 'test'; // 定義靜態屬性
console.log('靜態屬性',Parent.type) // 靜態屬性 test
let v_parent = new Parent();
console.log(v_parent); // {name: "xiaxaioxian"} 沒有tell方法和type屬性看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。