在 JavaScript 的 箭頭函式 (Arrow Function, =>
) 中,this
的行為與傳統的 函式表達式 (Function Expression) 不同,主要特點如下:
箭頭函式的 this
綁定
- 箭頭函式不會建立自己的
this
,而是繼承定義它的上下文(也稱為 詞法作用域 Lexical Scope)。 - 在箭頭函式內部,
this
指向的是箭頭函式所處的外部函式的this
值。
範例
1. 一般函式的 this
function normalFunction() { |
2. 箭頭函式的 this
const arrowFunction = () => { |
解析:
- **
arrowFunction
並未創建自己的this
,所以this
仍然指向外部作用域的this
**,而不是obj2
。
箭頭函式適用場景
1. 在物件方法中避免 this
綁定問題
const person = { |
解析:
setTimeout
中的箭頭函式不會創建新的this
,它會繼承sayHello
方法中的this
,所以this.name
正確指向person.name
。
若使用一般函式,
this
會指向window
(瀏覽器環境)或undefined
(嚴格模式)。
2. 當作回呼函式 (Callback)
const numbers = [1, 2, 3]; |
map()
內的箭頭函式不需要this
,但讓語法更簡潔。
箭頭函式的 this
限制
1. 不能作為建構函式 (Constructor)
const Person = (name) => { |
解法: 必須使用 function
來定義建構函式:
function Person(name) { |
2. 不能使用 arguments
const sum = () => { |
解法: 可以使用 展開運算符 ...args
const sum = (...args) => { |
3. 無法使用 .bind()
改變 this
const obj = { |
箭頭函式的
this
綁定無法透過bind()
、call()
或apply()
來改變。
總結
特性 | 一般函式 (Function) | 箭頭函式 (Arrow Function) |
---|---|---|
this |
依呼叫方式決定 | 繼承外部作用域 |
arguments |
有 (function 內部) |
無 (...args 取代) |
bind()/call()/apply() |
可改變 this |
無效 |
new 關鍵字 |
可用於建構函式 | 無法當建構函式 |
適用場景
適合使用箭頭函式:
- 短小的回呼函式 (e.g.
map
,filter
,forEach
) setTimeout()
或setInterval()
- 物件內部方法但不希望
this
被改變
不適合使用箭頭函式:
- 建構函式
- 需要動態
this
的方法 - 使用
arguments
物件的場合