class聲明一個animal類(對象):
class Animal{
constructor(){//這個constructor方法內定義的方法和屬性是實例化對象自己的,不共享;construstor外定義的方法和屬性是所有實例對象(共享)可以調用的
this.type = 'animal' //this關鍵字代表Animal對象的實例對象
}
says(say){
console.log(this.type+' says ' +say);
}
}
let animal = new Animal();
animal.says('hello');//控制檯輸出‘animal says hello’
這裏聲明一個Cat類,來繼承Animal類的屬性和方法
class Cat extends Animal(){
constructor(){
super();//super關鍵字,用來指定父類的實例對象
this.type = 'cat';
}
}
let cat = new Cat();
cat.says('hello');//輸出‘cat says hello’