ES6 提供了更接近傳統(tǒng)語(yǔ)言的寫法,引入了 Class(類)這個(gè)概念,作為對(duì)象的模板。通過class關(guān)鍵字,可以定義類。
定義類:
class Parent{
constructor(name,age){ // 類里自帶的構(gòu)造方法
this.name = name; // this是實(shí)例對(duì)象
this.age = age; // 設(shè)置屬性
}
play(){ // 設(shè)置方法
alert('我叫'+this.name);
}
}
ES6 的類相當(dāng)于構(gòu)造函數(shù)的另一種寫法
class Parent{
// ...
}
typeof Parent // "function"
類的數(shù)據(jù)類型是函數(shù),也就是指向構(gòu)造函數(shù)。
繼承:
Class 可以通過extends關(guān)鍵字實(shí)現(xiàn)繼承
class Child extends Parent{
constructor(name,age){
super(name,age); // 繼承父級(jí)的屬性,
this.sex = sex; // 子類沒有自己的this對(duì)象,而是繼承父類的this對(duì)象,進(jìn)行加工
}
showSex({
alert('我是'+this.sex+'的')
})
}