Javascript箭頭函式(ArrowFunctions)踩坑:this

慢慢地開始從老古板Javascript functions寫法轉向ES6的箭頭函式Arrow Functions寫法,不幸的因為jQuery踩到了一個Arrow Functions的坑,一切要從click事件說起。

jQuery的click事件

先說明,所有的問題都不關jQuery的click事件的事,程式碼如下:

<div>
  <span title="TestingTitle">SPAN With title</span>
  <span>Pure SPAN</span>
</div>
//所有的span有出現title屬性的都select
$("span[title]").click(function(){
  alert("TitleSpan: " + $(this)[0].constructor);
});
//所有的span都select
$("span").click(() => {
  alert("PureSpan: " + $(this)[0].constructor);
});

在還沒有踩到坑之前,我一直以為這兩個method抓到的$(this)理論上應該會一樣的,會踩到這個坑是因為我發現為何我的$(this)操作總是回傳給我沒有這個屬性之類的錯誤?經過不斷的黑人問號後才發現...箭頭函式根本沒有this。

以上面的程式碼來說,當使用者點選了具備Title的span,會跳出兩個alert訊息如下:

//第一個可理解,這是我們期待的this物件回傳。
TitleSpan: function HTMLSpanElement() { [native code] }

//第二個this回傳Window物件是三小?
PureSpan: function Window() { [native code] }

使用前請詳閱公開說明書

去MDN一查才發現,人家開宗明義就跟你聲明請不要把箭頭函式(Arrow function expressions)當作method,因為他的this會去抓當前宣告語法的父層物件,而因為我們的jQuery寫法是寫在Javascript的root scope,所以抓到最上層的Window物件,原文如下,唉~

Does not have its own bindings to this or super, and should not be used as methods.

心得筆記

使用箭頭函式Arrow Functions用到this寫法要非常謹慎,甚至最好不要用。

Javascript ArrowFunctions this $(this) jQuery ClickMethod