一、技術(shù)債務(wù)的隱形陷阱
1.this 綁定災(zāi)難
-箭頭函數(shù)繼承父作用域的 this,導(dǎo)致事件處理器、對(duì)象方法中邏輯崩潰
// 錯(cuò)誤示范:按鈕點(diǎn)擊事件中 this 指向錯(cuò)誤
button.addEventListener('click', () => {
console.log(this); // 輸出 window 而非 DOM 元素:ml-citation{ref="6" data="citationList"}
});
2.原型方法污染
-類中箭頭函數(shù)會(huì)為每個(gè)實(shí)例創(chuàng)建獨(dú)立函數(shù),破壞原型鏈復(fù)用機(jī)制
class User {
constructor(name) {
this.name = name;
this.greet = () => console.log(`Hi, ${this.name}`); // ? 實(shí)例污染
this.sayHello = function() { /* ? 正確綁定 */ };
}
}
二、被大廠限制使用的原因
1.不能作為構(gòu)造函數(shù) :箭頭函數(shù)沒有自己的 this ,無(wú)法通過 new 關(guān)鍵字實(shí)例化對(duì)象
- 事件處理器中不適用 :在需要?jiǎng)討B(tài) this (指向觸發(fā)事件的元素)的場(chǎng)景,箭頭函數(shù)會(huì)導(dǎo)致 this 指向錯(cuò)誤
3.缺少arguments對(duì)象 :箭頭函數(shù)中沒有 arguments 對(duì)象,如需可變參數(shù)需使用剩余參數(shù) ...args - 無(wú)法改變this指向 :不能通過 call 、 apply 、 bind 方法改變箭頭函數(shù)的 this 指向
- 不支持Generator函數(shù) :箭頭函數(shù)不能使用 yield 命令,無(wú)法作為Generator函數(shù)
替代方案與最佳實(shí)踐
1.嚴(yán)格模式下的函數(shù)聲明
// 推薦:顯式綁定 this
const safeCallback = function() {
console.log(this.value); // 明確上下文
}.bind(this);
2.現(xiàn)代語(yǔ)法替代方案
-使用 class 方法而非箭頭函數(shù)
-通過 Object.defineProperty 實(shí)現(xiàn)屬性代理