在 JavaScript 中,this 是一個關鍵字,它的值會根據執行環境的不同而改變。以下是 this 在不同情境下的行為:
1. 全域環境 (Global Context)
在瀏覽器中,this 預設指向 window 物件:
console.log(this); // 在瀏覽器中,this 指向 window |
在 Node.js 環境下,this 則指向 global:
console.log(this); // 在 Node.js 中,this 指向 global |
2. 函式內部 (Function Context)
在一般函式中,this 的值取決於是否使用 "use strict":
function showThis() { |
3. 物件方法 (Object Method)
當 this 被用在物件的方法內,它指向該物件:
const obj = { |
4. 建構函式 (Constructor Function)
在建構函式中,this 會指向新建立的物件:
function Person(name) { |
5. 箭頭函式 (Arrow Function)
箭頭函式中的 this 不會 指向它自己的執行環境,而是繼承自外層函式的作用域:
const obj = { |
6. setTimeout 和 setInterval
在 setTimeout 或 setInterval 內,一般函式的 this 預設指向 window (瀏覽器) 或 global (Node.js):
const obj = { |
解法:改用箭頭函式:
const obj = { |
7. 事件處理器 (Event Handler)
在事件處理函式中,this 指向觸發事件的元素:
document.getElementById("btn").addEventListener("click", function () { |
如果改用箭頭函式,this 會指向外部作用域:
document.getElementById("btn").addEventListener("click", () => { |
8. call、apply 和 bind
可以使用 call()、apply() 和 bind() 來改變 this 指向:
call()
function greet() { |
apply()
apply() 與 call() 類似,但參數是以陣列方式傳入:
function introduce(age, city) { |
bind()
bind() 會回傳一個新的函式,永久綁定 this:
const boundFunc = greet.bind(person); |
總結
- 全域環境:
this在瀏覽器中指向window,在 Node.js 指向global - 普通函式:嚴格模式下
this為undefined,否則指向window - 物件方法:
this指向該物件 - 建構函式:
this指向新建立的物件 - 箭頭函式:
this繼承外部作用域 - 事件處理器:普通函式
this指向事件元素,箭頭函式this指向外部作用域 call、apply、bind可顯式設定this