四種不應(yīng)該使用箭頭函數(shù)的情況
箭頭函數(shù)給我們的工作帶來了極大的方便,但是它們有什么缺點(diǎn)呢?我們應(yīng)該一直使用箭頭函數(shù)嗎?我們應(yīng)該在哪些場景中停止使用箭頭函數(shù)?
現(xiàn)在,我們開始吧。
箭頭函數(shù)的一些缺點(diǎn)
1、不支持參數(shù)對象
在箭頭函數(shù)中,我們不能像在普通函數(shù)中那樣使用 arguments 對象。
const fn1 = () => {
console.log('arguments', arguments)
}
fn1('fatfish', 'medium')
function fn2(){
console.log('arguments', arguments)
}
fn2('fatfish', 'medium')
可以看到,fn1箭頭函數(shù)報(bào)錯,但是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 都打印對象,我們應(yīng)該怎么做?
代碼:
const thisObj = {
name: 'fatfish'
}
const fn1 = () => {
console.log('this-fn1', this)
}
fn1.call(thisObj)
function fn2(){
console.log('this-fn2', this)
}
fn2.call(thisObj)
因?yàn)榧^函數(shù)在定義的時(shí)候就決定了它的this指向誰,所以沒有辦法用fn1.call(thisObj)再次改變它。
什么時(shí)候不能使用箭頭功能?
箭頭函數(shù)不是萬能的,至少有 4 種情況我們不應(yīng)該使用它們。
1、請不要在構(gòu)造函數(shù)中使用箭頭函數(shù)
function Person (name, age) {
this.name = name
this.age = age
}
const Person2 = (name, sex) => {
this.name = name
this.sex = sex
}
console.log('Person', new Person('fatfish', 100))
console.log('Person2', new Person2('fatfish', 100))
為什么 new Person2 會拋出錯誤?
因?yàn)闃?gòu)造函數(shù)通過 new 關(guān)鍵字生成一個(gè)對象實(shí)例。生成對象實(shí)例的過程也是通過構(gòu)造函數(shù)將this綁定到實(shí)例的過程。
但是箭頭函數(shù)沒有自己的this,所以不能作為構(gòu)造函數(shù)使用,也不能通過new操作符調(diào)用。
2、請不要在點(diǎn)擊事件中操作this
我們經(jīng)常在 click 事件中通過 this 讀取元素本身。
const $body = document.body
$body.addEventListener('click', function () {
// this and $body elements are equivalent
this.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”,因?yàn)榇藭r(shí)this和window是等價(jià)的,不等于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ū)給我留言,我們一起學(xué)習(xí)進(jìn)步;如果你覺得我今天的內(nèi)容對你有幫助的話,請記得點(diǎn)贊我,關(guān)注我,并將它分享給你身邊的朋友,也許能夠幫助到他。
最后,感謝你的閱讀,祝編程愉快!