了解TypeScript中函數(functions)的this概念

了解TypeScript中函數(functions)的this概念

TypeScript 函數(functions)的this

TypeScript 是一種 JavaScript 的超集,它擁有 JavaScript 的所有功能,並且提供了額外的特性,例如類型檢查、接口、泛型等等。在 TypeScript 中,函數也是一種重要的概念,它們可以被用來封裝一組相關的操作,並且可以被重複使用。

在 TypeScript 中,函數的 this 指向的是函數的呼叫者,而不是函數本身。這個概念可以被用來實現一些非常有用的功能,例如可以在函數中訪問函數的呼叫者的屬性和方法。

示例

假設我們有一個 Person 類別,它有一個名為 sayHello 的函數,它可以用來打招呼:

class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

現在,我們可以創建一個 Person 實例,並調用它的 sayHello 方法:

let person = new Person("John", 30);
person.sayHello(); // Hello, my name is John

在這個例子中,sayHello 方法的 this 指向的是 person 實例,所以我們可以在函數中訪問 person 實例的屬性,例如 name。

總結

在 TypeScript 中,函數的 this 指向的是函數的呼叫者,而不是函數本身。這個概念可以被用來實現一些非常有用的功能,例如可以在函數中訪問函數的呼叫者的屬性和方法。

推薦閱讀文章

推薦閱讀文章

            <a href="https://www.tutorialsteacher.com/typescript/this-keyword-in-typescript">TypeScript 中的 this 關鍵字</a><br>
            <a href="https://www.typescriptlang.org/docs/handbook/functions.html">TypeScript 函數</a><br>
            <a href="https://www.typescriptlang.org/docs/handbook/functions.html#this">TypeScript 函數的 this</a><br>
            <a href="https://www.freecodecamp.org/news/typescript-this-keyword-understanding-and-usage/">理解和使用 TypeScript 中的 this 關鍵字</a><br>
            <a href="https://www.sitepoint.com/understanding-typescript-this/">理解 TypeScript 中的 this</a

延伸閱讀本站文章

更多TypeScript相關文章

推薦學習youtube影片

發佈留言