DIV CSS 佈局教程網

JavaScript 與 jQuery 中 this 關鍵字的用法與差異
編輯:關於JavaScript     

this 是 JavaScript 最容易搞混的關鍵字之一。它的值取決於「函式怎麼被呼叫」,而不是「函式在哪裡定義」。本文用兩個小範例說明原生 JS 與 jQuery 中的差異。

原生 JavaScript:this 就是觸發事件的元素

<script type="text/javascript">
function chimg(obj) {
  obj.src = "./images/2.jpg";
}
</script>
<img src="./images/1.jpg" onclick="chimg(this)">

這裡的 this 出現在行內事件屬性中,指向目前的 img 元素本身。把它當參數傳進 chimg,函式內就能直接改它的 src,點一下圖片就換圖。

jQuery:this 是 DOM 元素,不是 jQuery 物件

<script type="text/javascript">
$(document).ready(function () {
  alert(this.src);
});
</script>
<img src="./images/1.jpg" class="img">

在事件回呼或 each 迴圈中,jQuery 會把 this 設定為原始的 DOM 元素,所以 this.src 可以直接取用。

最常見的錯誤

新手最常踩的坑,是把 jQuery 的方法用在 this 上:

$('.img').click(function () {
  this.css('color', 'red');   // 錯誤!this 是 DOM 元素,沒有 css 方法
  $(this).css('color', 'red'); // 正確,先用 $() 包裝
});

反過來也一樣常見:已經用 $(this) 包裝了,卻又試圖存取 DOM 的屬性:

$('.img').click(function () {
  $(this).src = '2.jpg';        // 不會作用,jQuery 物件上沒有 src
  this.src = '2.jpg';           // 正確
  $(this).attr('src', '2.jpg'); // 也可以
});

記法很簡單:this 是 DOM 元素,$this 是 jQuery 物件。兩者需要轉換,轉換成本很低,但混淆了就會出錯。

箭頭函式帶來的變化

ES6 的箭頭函式沒有自己的 this,它會沿用外層作用域的 this。這在物件方法中很方便,但在需要元素參照的事件回呼中會適得其反而:

$('.img').click(() => {
  console.log(this);  // 這裡的 this 不是 img,而是外層的 this(通常是 window 或 undefined)
});

所以在 jQuery 事件回呼中,若需要元素本身,請使用 function 而非箭頭函式;或者用事件物件:

$('.img').click((e) => {
  console.log(e.currentTarget);  // 透過事件物件取得元素
});

this 的四種綁定規則

  1. 預設綁定:獨立呼叫 fn(),非嚴格模式下 this 是 window,嚴格模式下是 undefined。
  2. 隱含綁定:obj.fn(),this 是 obj。這也是 obj.method() 形式的由來。
  3. 明確綁定:call、apply、bind 可以指定 this。
  4. new 綁定:用 new 呼叫建構函式時,this 指向新建立的物件。

優先順序為:new > 明確綁定 > 隱含綁定 > 預設綁定。箭頭函式則完全不受這些規則影響。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved