[ES6學習筆記 (三)]類別與物件

  • 476
  • 0
  • ES6
  • 2018-01-04

其實整個寫法都還滿像JAVA的....

 

1.定義類別與產生物件
//定義類別
class SuperHero{
	
}

//建立物件
var ironMan = new SuperHero();
var superMan = new SuperHero();

 

2.建構式(Constructor)
class SuperHero{
  constructor(){
    console.log("建構式");
  }	
}

var ironMan = new SuperHero();//產生物件時會呼叫建構式
var superMan = new SuperHero();//產生物件時會呼叫建構式

//若沒寫建構式,會預設給一組空的 constructor(){}

 

3.屬性
class SuperHero{
  constructor(pName){
    this.name = pName;
  }	
}

var ironMan = new SuperHero("鋼鐵人");
var superMan = new SuperHero("超人");

console.log(ironMan.name); //鋼鐵人
console.log(superMan.name); //超人

 

4.方法
class SuperHero{
  constructor(pName){
    this.name = pName;
    this.speend = 0;
  }	
	
  fly(pSpeed){
    this.speend = pSpeed;
    console.log(this.name + " is flying... (" + this.speend + " KM/HR )");
  }
}

var ironMan = new SuperHero("鋼鐵人");
var superMan = new SuperHero("超人");

ironMan.fly(100); //鋼鐵人 is flying... ( 100 KM/HR )
superMan.fly(20); //超人 is flying... (20 KM/HR )