一、箭頭函數的基本特性
- 語法簡潔性
箭頭函數使用=>
符號定義,省略function
關鍵字,適合快速定義匿名函數或簡單表達式。
// 普通函數
function sum(a, b) { return a + b; }
// 箭頭函數
const sum = (a, b) => a + b;
若函數體為單行表達式,可省略 {}
和 return
。
-
匿名性
箭頭函數均為匿名函數,不能通過function
命名。 -
隱式返回對象
返回對象字面量時需用()
包裹,避免與函數體的大括號沖突:
const getObj = id => ({ id: id }); // 正確
二、this
指向的核心差異
-
普通函數的
this
-
動態綁定:根據調用方式確定
this
(如對象方法調用、構造函數調用等)。 -
可通過
call
、apply
、bind
顯式修改this
指向。
-
-
示例?:
const obj = {value: 10,getValue: function() { return this.value; }
};
obj.getValue(); // 10(this指向obj)
-
箭頭函數的
this
-
詞法綁定?:在定義時捕獲外層非箭頭函數的
this
,且無法通過調用方式改變。 -
**無自身
this
**:相當于“繼承”父級上下文的this
。
-
-
示例?:
function Timer() {this.seconds = 0;// 箭頭函數捕獲外層Timer的thissetInterval(() => this.seconds++, 1000);
}
const timer = new Timer(); // this.seconds每秒自增
三、箭頭函數與普通函數的其他區別
四、this
的具體應用場景對比
-
對象方法
- 普通函數?:
this
指向調用對象。
const obj = {value: 10,getValue() { return this.value; } // 返回10 };
- 箭頭函數?:
this
指向外層作用域(如全局window
)。
const obj = {value: 10,getValue: () => this.value // 返回undefined(全局無value) };
- 普通函數?:
-
事件處理函數
-
普通函數?:
this
指向觸發事件的 DOM 元素。 -
箭頭函數?:
this
指向定義時的外層作用域(可能不符合預期)。
-
-
高階函數(如
map
、setTimeout
)?
優先使用箭頭函數避免this
丟失:
// 傳統函數需綁定this
arr.map(function(item) { return item * this.factor; }.bind(this));
// 箭頭函數自動捕獲外層this
arr.map(item => item * this.factor);
五、適用場景總結
-
優先使用箭頭函數?:
-
需要固定
this
的場景(如回調函數、事件處理)。 -
簡化單行表達式(如數組操作
map
/filter
)。
-
-
避免使用箭頭函數?:
- 對象方法、構造函數、需要
arguments
的場景。
- 對象方法、構造函數、需要