關鍵點
1、class 可以理解爲function,由於class本質還是一個function,因此它也會擁有一個的prototype屬性,當new一個class時,會把class的porototype屬性賦值給這個新對象的 __proto屬性。
2、constructor 方法是默認添加的方法,在new一個對象時,自動調用該方法,constructor裏面定義自己的屬性。
3、繼承extends和super,class 子類名 extends 父類名實現繼承,當然還得在constructor裏面寫上super(父類的參數),意思就是在子類中獲得父類的this指針,相當於Animal.call(this)。
// es6繼承
class Animal {
//構造函數,裏面寫上對象的屬性
constructor(props) {
this.name = props.name || 'Unknown';
}
//方法寫在後面
eat() {//父類共有的方法
console.log(this.name + " will eat pests.");
}
}
//class繼承
class Bird extends Animal {
//構造函數
constructor(props,myAttribute) {//props是繼承過來的屬性,myAttribute是自己的屬性
//調用實現父類的構造函數
super(props)//相當於獲得父類的this指向
this.type = props.type || "Unknown";//父類的屬性,也可寫在父類中
this.attr = myAttribute;//自己的私有屬性
}
fly() {//自己私有的方法
console.log(this.name + " are friendly to people.");
}
myattr() {//自己私有的方法
console.log(this.type+'---'+this.attr);
}
}
//通過new實例化
var myBird = new Bird({
name: '小燕子',
type: 'Egg animal'//卵生動物
},'Bird class')
myBird.eat()
myBird.fly()
myBird.myattr()