這樣就會跟原本的 javascipt 一樣 想怎麼塞就怎麼塞 也可以乖乖的寫成 let myFavoriteNumber: string | number;
class 類別
有接觸過 es6 的人應該對 class 不陌生,以前如果要實作繼承的話,必須透過 function + prototype 來達成,但 es6 提供了 class 這個一種語法糖,並不是真的是以類別為基礎(class-based)的物件導向,實際上仍然是以原型為基礎(prototype-based)的物件導向,另外,class 的名稱須採用大駝峰(ClassName)的寫法,但實測全部小寫也不會編譯不過,但還是要遵循規範,乖乖用駝峰式囉。
classComputer{ public name: string="" constructor(name){ this.name=name } public rebooting(){ console.log(`your ${this.name} will rebooting in a minute`); } }
letNB = newComputer("Notbook") letDeskTop = newComputer(‘DeskTop’) NB.rebooting() // 輸出 your Notbook will rebooting in a minute
DeskTop.rebooting() // 輸出 your DeskTop will rebooting in a minute
inheritance 繼承
利用 extends 來繼承 class,會在 constructor 呼叫 super 方法 => 執行父類別的 constructor,可以透過 super 來取用父層的方法或屬性 。那一定要寫 super 嗎?答案是肯定的,沒調用 super 方法會編譯失敗之外,想要取 this.name 的值也會取不到,因為此時的 this 不知道要指向誰,只有在執行完 super 之後,this 才會指向物件本身。
classComputer{ public name: string="" constructor(name){ this.name=name } public rebooting(){ console.log(`your ${this.name} will rebooting in a minute`); } }
classPerson{ age: number=100 public name: string public height: number=180 private id: number=147896523 protected gender: string=’unknown’ constructor(name){ this.name=name } public walking(){ console.log('${this.name} walking in the rain'); } }
//子類別
classTomextendsPerson{ constructor(){ super("Tom") } public getGender(){ console.log('my gender is ${this.gender}') } }
let personHeight = newPerson("Marry").height//可以取用 let personID = newPerson("Marry").personID//報錯 不允許外部取用 let personGender = newPerson("Marry").gender//報錯 僅限定子類別取用
Static 靜態屬性
直接定義在類別身上 不需要實例化就可以取用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classCat { staticvoice: string = "meow"; constructor() {} staticsayHi() { console.log("${this.voice}~${this.voice}~"); } } //注意,如果静态方法包含 this 关键字,这个 this 指的是类,而不是实例。 classFatCatextendsCat {}