四種不應(yīng)該使用箭頭函數(shù)的情況
箭頭函數(shù)給我們的工作帶來(lái)了極大的方便,但是它們有什么缺點(diǎn)呢?我們應(yīng)該一直使用箭頭函數(shù)嗎?我們應(yīng)該在哪些場(chǎng)景中停止使用箭頭函數(shù)?
現(xiàn)在,我們開(kāi)始吧。
箭頭函數(shù)的一些缺點(diǎn)
1、不支持參數(shù)對(duì)象
在箭頭函數(shù)中,我們不能像在普通函數(shù)中那樣使用 arguments 對(duì)象。
const fn1 = () => {
console.log('arguments', arguments)
}
fn1('fatfish', 'medium')
function fn2(){
console.log('arguments', arguments)
}
fn2('fatfish', 'medium')
可以看到,fn1箭頭函數(shù)報(bào)錯(cuò),但是fn2可以正常讀取arguments對(duì)象。
我們?nèi)绾尾拍茉诩^函數(shù)中獲取所有傳遞給函數(shù)的參數(shù)?
是的,沒(méi)錯(cuò),你可以使用Spread Operator來(lái)解決它。
const fn3 = (values) => {
console.log('values', values)
}
fn3('fatfish', 'medium')
2、無(wú)法通過(guò)apply、call、bind來(lái)改變this指針
我相信你可以很容易地知道下面的代碼會(huì)輸出什么。
const fn1 = () => {
console.log('this-fn1', this)
}
fn1()
function fn2(){
console.log('this-fn2', this)
}
fn2()
{
name: 'fatfish'
}
我們希望 fn1 和 fn2 都打印對(duì)象,我們應(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指向誰(shuí),所以沒(méi)有辦法用fn1.call(thisObj)再次改變它。
什么時(shí)候不能使用箭頭功能?
箭頭函數(shù)不是萬(wàn)能的,至少有 4 種情況我們不應(yīng)該使用它們。
1、請(qǐng)不要在構(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 會(huì)拋出錯(cuò)誤?
因?yàn)闃?gòu)造函數(shù)通過(guò) new 關(guān)鍵字生成一個(gè)對(duì)象實(shí)例。生成對(duì)象實(shí)例的過(guò)程也是通過(guò)構(gòu)造函數(shù)將this綁定到實(shí)例的過(guò)程。
但是箭頭函數(shù)沒(méi)有自己的this,所以不能作為構(gòu)造函數(shù)使用,也不能通過(guò)new操作符調(diào)用。
2、請(qǐng)不要在點(diǎn)擊事件中操作this
我們經(jīng)常在 click 事件中通過(guò) this 讀取元素本身。
const $body = document.body
$body.addEventListener('click', function () {
// this and $body elements are equivalent
this.innerHTML = 'fatfish'
})
但是如果你使用箭頭函數(shù)給 DOM 元素添加回調(diào),這將等同于全局對(duì)象窗口。
const $body = document.body
$body.addEventListener('click', () => {
this.innerHTML = 'fatfish'
})
3、請(qǐng)不要在對(duì)象的方法中使用箭頭函數(shù)。
const obj = {
name: 'fatfish',
getName () {
return this.name
},
getName2: () => {
return this.name
}
}
console.log('getName', obj.getName())
console.log('getName2', obj.getName2())
你知道這段代碼會(huì)輸出什么嗎?
是的,getName2方法不會(huì)打印“fatfish”,因?yàn)榇藭r(shí)this和window是等價(jià)的,不等于obj。
4、請(qǐng)不要在原型鏈中使用箭頭函數(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()
寫(xiě)在最后
以上這4種情況中,不建議使用箭頭函數(shù),如果你還了解其他的情況的話,也請(qǐng)你在留言區(qū)給我留言,我們一起學(xué)習(xí)進(jìn)步;如果你覺(jué)得我今天的內(nèi)容對(duì)你有幫助的話,請(qǐng)記得點(diǎn)贊我,關(guān)注我,并將它分享給你身邊的朋友,也許能夠幫助到他。
最后,感謝你的閱讀,祝編程愉快!