這里已經(jīng)清楚了說(shuō)明了,箭頭函數(shù)沒有自己的 this 綁定。箭頭函數(shù)中使用的 this,其實(shí)是直接包含它的那個(gè)函數(shù)或函數(shù)表達(dá)式中的 this。比如
const obj = { test() { const arrow = () => { // 這里的 this 是 test() 中的 this, // 由 test() 的調(diào)用方式?jīng)Q定 console.log(this === obj); }; arrow(); }, getArrow() { return () => { // 這里的 this 是 getArrow() 中的 this, // 由 getArrow() 的調(diào)用方式?jīng)Q定 console.log(this === obj); }; } }; obj.test(); // true const arrow = obj.getArrow(); arrow(); // true
示例中的兩個(gè) this 都是由箭頭函數(shù)的直接外層函數(shù)(方法)決定的,而方法函數(shù)中的 this 是由其調(diào)用方式?jīng)Q定的。上例的調(diào)用方式都是方法調(diào)用,所以 this 都指向方法調(diào)用的對(duì)象,即 obj。
箭頭函數(shù)讓大家在使用閉包的時(shí)候不需要太糾結(jié) this,不需要通過(guò)像 _this 這樣的局部變量來(lái)臨時(shí)引用 this 給閉包函數(shù)使用。來(lái)看一段 Babel 對(duì)箭頭函數(shù)的轉(zhuǎn)譯可能能加深理解:
// ES6 const obj = { getArrow() { return () => { console.log(this === obj); }; } }
// ES5,由 Babel 轉(zhuǎn)譯 var obj = { getArrow: function getArrow() { var _this = this; return function () { console.log(_this === obj); }; } };
另外需要注意的是,箭頭函數(shù)不能用 new 調(diào)用,不能 bind() 到某個(gè)對(duì)象(雖然 bind() 方法調(diào)用沒問(wèn)題,但是不會(huì)產(chǎn)生預(yù)期效果)。不管在什么情況下使用箭頭函數(shù),它本身是沒有綁定 this 的,它用的是直接外層函數(shù)(即包含它的最近的一層函數(shù)或函數(shù)表達(dá)式)綁定的 this。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com