精簡(jiǎn)的函數(shù)快遞員
想象箭頭函數(shù)是一位高效的快遞員,用最短路徑(=>
)傳遞數(shù)據(jù)
function add(a, b) {
return a + b;
}
const add = (a, b) => a + b;
console.log(add(1, 2));
精簡(jiǎn)規(guī)則
單參數(shù)可省括號(hào)
const sayHi = name => `你好, ${name}!`;
sayHi("小明");
單行代碼自動(dòng)返回(無(wú){}
時(shí))
const double = num => num * 2;
返回對(duì)象需加括號(hào)(避免與{}
沖突)
const getUser = id => ({ id: id, name: "匿名" });
永不迷路的 this
箭頭函數(shù)最強(qiáng)大的特性——繼承外層 this
值,解決傳統(tǒng)函數(shù)的 this
混亂問(wèn)題
const obj1 = {
name: "對(duì)象1",
print: function() {
setTimeout(function() {
console.log(this.name);
}, 100);
}
};
const obj2 = {
name: "對(duì)象2",
print: function() {
setTimeout(() => {
console.log(this.name);
}, 100);
}
};
箭頭函數(shù)就像帶著GPS的快遞員,永遠(yuǎn)記得出發(fā)地(定義時(shí)的作用域),不因中轉(zhuǎn)站(調(diào)用位置)改變路線
一般常見(jiàn)的使用場(chǎng)景
簡(jiǎn)化回調(diào)函數(shù)
[1, 2, 3].map(function(x) { return x * x; });
[1, 2, 3].map(x => x * x);
操作數(shù)組方法
const sum = [1, 2, 3].reduce((total, num) => total + num, 0);
固定 this 的場(chǎng)景(如事件監(jiān)聽(tīng))
button.addEventListener("click", () => {
console.log(this);
});
箭頭函數(shù) vs 普通函數(shù)
特性 | 箭頭函數(shù) | 普通函數(shù) |
---|
this 指向 | 繼承定義時(shí)的外層作用域 | 由調(diào)用者決定 |
構(gòu)造函數(shù) | ? 不可用 | ? 可用 |
arguments 對(duì)象 | ? 不可用 | ? 可用 |
簡(jiǎn)潔性 | ???? 極高 | ?? 較低 |
牢記
“箭頭函數(shù)像快遞:路線短(語(yǔ)法簡(jiǎn)),認(rèn)準(zhǔn)出發(fā)地(this穩(wěn)),不接大件貨(無(wú)構(gòu)造)。”
轉(zhuǎn)自https://juejin.cn/post/7546445334568468507
該文章在 2025/9/6 17:24:48 編輯過(guò)