4 種不應該使用箭頭函數(shù)的情況

const fn1 = () => {console.log('arguments', arguments)}fn1('fatfish', 'medium')function fn2(){console.log('arguments', arguments)}fn2('fatfish', 'medium')
可以看到,fn1箭頭函數(shù)報錯,但是fn2可以正常讀取arguments對象。

我們?nèi)绾尾拍茉诩^函數(shù)中獲取所有傳遞給函數(shù)的參數(shù)?
是的,沒錯,你可以使用Spread Operator來解決它。
const fn3 = (...values) => {console.log('values', values)}fn3('fatfish', 'medium')
2、無法通過apply、call、bind來改變this指針
我相信你可以很容易地知道下面的代碼會輸出什么。
const fn1 = () => {console.log('this-fn1', this)}fn1()function fn2(){console.log('this-fn2', this)}fn2()

{name: 'fatfish'}
我們希望 fn1 和 fn2 都打印對象,我們應該怎么做?
代碼:
const thisObj = {name: 'fatfish'}const fn1 = () => {console.log('this-fn1', this)}fn1.call(thisObj)function fn2(){console.log('this-fn2', this)}fn2.call(thisObj)
因為箭頭函數(shù)在定義的時候就決定了它的this指向誰,所以沒有辦法用fn1.call(thisObj)再次改變它。
什么時候不能使用箭頭功能?
箭頭函數(shù)不是萬能的,至少有 4 種情況我們不應該使用它們。
1、請不要在構(gòu)造函數(shù)中使用箭頭函數(shù)
function Person (name, age) {this.name = namethis.age = age}const Person2 = (name, sex) => {this.name = namethis.sex = sex}console.log('Person', new Person('fatfish', 100))console.log('Person2', new Person2('fatfish', 100))
為什么 new Person2 會拋出錯誤?
因為構(gòu)造函數(shù)通過 new 關鍵字生成一個對象實例。生成對象實例的過程也是通過構(gòu)造函數(shù)將this綁定到實例的過程。
但是箭頭函數(shù)沒有自己的this,所以不能作為構(gòu)造函數(shù)使用,也不能通過new操作符調(diào)用。
2、請不要在點擊事件中操作this
我們經(jīng)常在 click 事件中通過 this 讀取元素本身。
const $body = document.body$body.addEventListener('click', function () {// this and $body elements are equivalentthis.innerHTML = 'fatfish'})
但是如果你使用箭頭函數(shù)給 DOM 元素添加回調(diào),這將等同于全局對象窗口。
const $body = document.body$body.addEventListener('click', () => {this.innerHTML = 'fatfish'})
3、請不要在對象的方法中使用箭頭函數(shù)。
const obj = {name: 'fatfish',getName () {return this.name},getName2: () => {return this.name}}console.log('getName', obj.getName())console.log('getName2', obj.getName2())
你知道這段代碼會輸出什么嗎?
是的,getName2方法不會打印“fatfish”,因為此時this和window是等價的,不等于obj。

4、請不要在原型鏈中使用箭頭函數(shù)
const Person = function (name) {this.name = name}Person.prototype.showName = function () {console.log('showName', this, this.name)}Person.prototype.showName2 = () => {console.log('showName2', this, this.name)}const p1 = new Person('fatfish', 100)p1.showName()p1.showName2()
寫在最后
以上這4種情況中,不建議使用箭頭函數(shù),如果你還了解其他的情況的話,也請你在留言區(qū)給我留言,我們一起學習進步;如果你覺得我今天的內(nèi)容對你有幫助的話,請記得點贊我,關注我,并將它分享給你身邊的朋友,也許能夠幫助到他。
最后,感謝你的閱讀,祝編程愉快!
學習更多技能
請點擊下方公眾號
![]()

