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