class 類別
名詞解釋
§ 類別(class):沒有實體概念, 是個藍圖, 參考文件, 屬於靜態, 可建立許實體。 § 物件(object):是個實體, 狀態會改變, 但架構跟行為不會變, 屬於動態。
class 的繼承
§ 使用 extends 會繼承父元素所有屬性和方法 § 子類別中的 constructor (建構函式), 需用 super 來拿取父類別中的 constructor 才會有 this 關鍵字。
class 中,定義 instence 的屬性
§ new 出一個 instence 時,一定會執行 constructor 方法 § class 裡的 this,是指向 instence
範例
// 父類別
class Bird {
constructor (age) {
this.age = age; =====> class 內的 this 指向實體(instence)
}
}
const birdAge = new Bird(18); =====> new 出一個實體並執行建構函式方法
// 子類別
class RedBird extends Bird {
constructor (age, color) {
super(age); =====> 呼叫父類別的建構函式的 age
this.color = color; =====> this 只會在 super 後面
}
}
const newBirdr = new RedBird(25, “red”) ====> 實體的方法&屬性要用 new 拿出來