這里已經(jīng)清楚了說明了,箭頭函數(shù)沒有自己的 this 綁定。箭頭函數(shù)中使用的 this,其實是直接包含它的那個函數(shù)或函數(shù)表達式中的 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
示例中的兩個 this 都是由箭頭函數(shù)的直接外層函數(shù)(方法)決定的,而方法函數(shù)中的 this 是由其調(diào)用方式?jīng)Q定的。上例的調(diào)用方式都是方法調(diào)用,所以 this 都指向方法調(diào)用的對象,即 obj。
箭頭函數(shù)讓大家在使用閉包的時候不需要太糾結 this,不需要通過像 _this 這樣的局部變量來臨時引用 this 給閉包函數(shù)使用。來看一段 Babel 對箭頭函數(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() 到某個對象(雖然 bind() 方法調(diào)用沒問題,但是不會產(chǎn)生預期效果)。不管在什么情況下使用箭頭函數(shù),它本身是沒有綁定 this 的,它用的是直接外層函數(shù)(即包含它的最近的一層函數(shù)或函數(shù)表達式)綁定的 this。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com