在 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物件的場合