Try   HackMD

Getter

在上一篇文章,我們談論 public 時有個範例:

class Rectangle { public width: number = 100; // 建構式 constructor() { this.width = 50; } changeVal(): void { this.width = 80; } }

以這個範例來看,若我們想要透過 changeVal() 直接回傳 width 值,而不改變它,我們可以在方法中使用 return

class Rectangle { public width: number = 100; // 建構式 constructor() { this.width = 50; } changeVal(): number { return this.width } } const square = new Rectangle(); console.log(square.changeVal()); // 80

這很直觀,就像一般的函式一樣。

不過為了後續的可讀性和可維護性,我們通常會將 純粹取值 的行為,與需要處理資料的 方法 個別獨立出來。

因此我們會選擇使用 GetterSetter 的機制,來回傳值當前的狀態,直接來看個範例:

class Rectangle { public width: number = 100; // 建構式 constructor() { this.width = 50; } get getWidth(): number { return this.width; } } const square = new Rectangle(); console.log(square.getWidth); // 非 square.getWidth()

我們在 getWidth() 前加上 get 關鍵字,呼叫時與先前不同,square.getWidth 不用加 ()

() 是為了呼叫方法,而使用 get 則是將其視為變數使用。

Setter

Getter 是為了取值,而 Setter 則是為了設值,我們會使用到 set 關鍵字:

class Rectangle { public width: number = 100; // 建構式 constructor() { this.width = 50; } get getWidth(): number { return this.width; } set setWidth(val: number) { this.width = val; } } const square = new Rectangle(); square.setWidth = 80; // 非 square.setWidth(80) console.log(square.getWidth); // 80

雖然宣告方式與 function 很像,需要宣告參數並且型別註記。
不過使用上則是和變數相同,直接透過 = 賦值即可。


Reference


系列:跑完 JS30 就接著認識 TypeScript 入門
上一篇:Day11:認識類別 Class - 封裝 Encapsulation
下一篇:Day13:認識類別 Class - 繼承 Inheritance

tags: 跑完 JS30 就接著認識 TypeScript 入門
Created on ∥ March 23, 2023
文章若有任何錯誤,還請不吝給予留言指正,謝謝大家!