es6聲明類實現繼承

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’
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章