您好,登錄后才能下訂單哦!
這篇“JS中不應(yīng)該使用箭頭函數(shù)的情況有哪些”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“JS中不應(yīng)該使用箭頭函數(shù)的情況有哪些”文章吧。
在箭頭函數(shù)中,我們不能像在普通函數(shù)中那樣使用 arguments 對象。
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')
我相信你可以很容易地知道下面的代碼會輸出什么。
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)
因為箭頭函數(shù)在定義的時候就決定了它的this指向誰,所以沒有辦法用fn1.call(thisObj)再次改變它。
箭頭函數(shù)不是萬能的,至少有 4 種情況我們不應(yīng)該使用它們。
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 會拋出錯誤
因為構(gòu)造函數(shù)通過 new 關(guān)鍵字生成一個對象實例。生成對象實例的過程也是通過構(gòu)造函數(shù)將this綁定到實例的過程。
但是箭頭函數(shù)沒有自己的this,所以不能作為構(gòu)造函數(shù)使用,也不能通過new操作符調(diào)用。
我們經(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' })
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。
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()
以上就是關(guān)于“JS中不應(yīng)該使用箭頭函數(shù)的情況有哪些”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。