--- GA: G-7BSJTG7RYN --- ### Getter 在上一篇文章,我們談論 `public` 時有個範例: ```typescript= class Rectangle { public width: number = 100; // 建構式 constructor() { this.width = 50; } changeVal(): void { this.width = 80; } } ``` 以這個範例來看,若我們想要透過 `changeVal()` 直接回傳 `width` 值,而不改變它,我們可以在方法中使用 `return`: ```typescript= class Rectangle { public width: number = 100; // 建構式 constructor() { this.width = 50; } changeVal(): number { return this.width } } const square = new Rectangle(); console.log(square.changeVal()); // 80 ``` 這很直觀,就像一般的函式一樣。 不過為了後續的可讀性和可維護性,我們通常會將 **純粹取值** 的行為,與需要處理資料的 **方法** 個別獨立出來。 因此我們會選擇使用 `Getter` 與 `Setter` 的機制,來回傳值當前的狀態,直接來看個範例: ```typescript= 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` 關鍵字: ```typescript= 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 - [TypeScript Official Site](https://www.typescriptlang.org/docs/) - [Classes (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) --- > 系列:[`跑完 JS30 就接著認識 TypeScript 入門`](https://hackmd.io/@elzuoc?tags=%5B%22%E8%B7%91%E5%AE%8C+JS30+%E5%B0%B1%E6%8E%A5%E8%91%97%E8%AA%8D%E8%AD%98+TypeScript+%E5%85%A5%E9%96%80%22%5D) > 上一篇:[Day11:認識類別 Class - 封裝 Encapsulation](https://hackmd.io/@elzuoc/HkVDUvFgh) > 下一篇:Day13:認識類別 Class - 繼承 Inheritance ###### tags: [`跑完 JS30 就接著認識 TypeScript 入門`](https://hackmd.io/@elzuoc?tags=%5B%22%E8%B7%91%E5%AE%8C+JS30+%E5%B0%B1%E6%8E%A5%E8%91%97%E8%AA%8D%E8%AD%98+TypeScript+%E5%85%A5%E9%96%80%22%5D) ###### Created on ∥ March 23, 2023 ###### 文章若有任何錯誤,還請不吝給予留言指正,謝謝大家!