深入解析 JavaScript this - 用 apply、call 和 bind 克服函式綁定挑戰
· 閱讀時間約 5 分鐘
在 JavaScript 中,this
的值取決於函式的呼叫上下文,而不是函式的定義位置。這使得 this 的行為有時候很難預測和控制。
首先我們先來複習一下 JavaScript 中 this
的行為:
this
在 JavaScript 中,this
是一 個很特別的關鍵字,它的值會根據它所在的環境而改變。簡單來說,this
指的是呼叫函式時的上下文(context),也就是「誰」在呼叫這個函式。
傳統函式中的 this
在傳統函式裡,this
的指向取決於函式是**「怎麼」被呼叫的**
const person = {
name: "Alice",
greet: function () {
console.log(`Hi, I'm ${this.name}`);
},
};
// 這個 greet 函式是透過 person 物件來呼叫的。
// 這意味著,JavaScript 會把 this 綁定到 person,讓 this.name 指向 person.name。
person.greet(); // Hi, I'm Alice
const greetFunction = person.greet;
// 這裡的 this 就指向 window 物件,因為 greetFunction 是直接被呼叫的。
// 這時候 this.name 就會是 undefined 或 window.name 的值。
greetFunction(); // Hi, I'm