[ES6學習筆記 (四)]類別的繼承

  • 483
  • 0
  • ES6
  • 2018-01-04

上一篇講怎麼建立類別與產生物件,這篇講述怎麼使用繼承的方式繼承類別,想法其實還是跟JAVA很像...就直接看範例就可以理解了...

 

1.繼承
//蝙蝠俠
class Batman{	
  constructor(){
    console.log("父類別的建構式");
  }			  
}


//惡夢蝙蝠俠繼承蝙蝠俠
class NightmareBatman extends Batman{
  constructor(){
    super();
    console.log("子類別的建構式");
  }			  
}

//產生子類別的物件時,會先呼叫「父類別的建構式」再呼叫「子類別的建構式」
var nightmareBatman = new NightmareBatman();

 

2.屬性
class Batman{
  constructor(pName){
    this.name = pName;
    this.height = 150;
  }			  
}

class NightmareBatman extends Batman{
  constructor(pName, pHeight){
    super(pName);
    this.height = pHeight;
  }
}

var nightmareBatman = new NightmareBatman("惡夢蝙蝠俠",200);
console.log(nightmareBatman.name); //惡夢蝙蝠俠
console.log(nightmareBatman.height); //200

 

3.方法
class Batman{
  constructor(pName){
    this.name = pName;
  }
  
  //父類別射擊的Method
  shoot(pGun){
  	this.gun = pGun;
  	console.log(this.name + " 拿 [" + this.gun + "]射擊..");
  }	  
}

class NightmareBatman extends Batman{
  constructor(pName){
    super(pName);
  }
}

var nightmareBatman = new NightmareBatman("惡夢蝙蝠俠");
nightmareBatman.shoot("AK47"); //惡夢蝙蝠俠 拿 [AK47]射擊..

 

4.「覆寫父類別的方法」與「新增子類別的方法」
class Batman{
  constructor(pName){
    this.name = pName;
  }
  //父類別射擊的Method
  shoot(pGun){
  	this.gun = pGun;
  	console.log(this.name + " 拿 [" + this.gun + "]射擊..");
  }
}

class NightmareBatman extends Batman{
  constructor(pName){
    super(pName);
  }

  //「覆寫」父類別射擊的Method
  shoot(){
    console.log(this.name + " 丟出 [蝙蝠標] ..!!");
  }

  //子類別的Method
  rich(){
    console.log(this.name + " 丟出 [$$$$$$$$$] ..!!");
  }
}

var nightmareBatman = new NightmareBatman("惡夢蝙蝠俠");
nightmareBatman.shoot("AK47"); //惡夢蝙蝠俠 拿 [AK47]射擊..
nightmareBatman.rich(); //惡夢蝙蝠俠 丟出 [$$$$$$$$$] ..!!