Skip to content

this 是什麼

在 Javascript 的世界中,this 的使用有些繁瑣,在這個章節 Away 會用幾個常見的狀態來說明。

全域環境

this 在全域的環境下運作會被當作全域物件,也就是 Window

js
// Window
console.log(this);

DOM 事件監聽

若 DOM 配合事件監聽器使用,this 會指向該 DOM。

html
<input id="Btn" type="button" value="mouseenter">
js
document.querySelector('#Btn').addEventListener('mouseenter', function () {
  // <input id="Btn" type="button" value="mouseenter">
  console.log(this);

  // Btn
  console.log(this.id);

  // button
  console.log(this.type);

  // mouseenter
  console.log(this.value);
});

呈上,我們可以利用 this.value 來改變 value 屬性的文字內容。

js
document.querySelector('#Btn').addEventListener('mouseenter', function () {
  this.value = 'mouseleave';
});

document.querySelector('#Btn').addEventListener('mouseleave', function () {
  this.value = 'mouseenter';
});

箭頭函式

箭頭函式是一個非常好用的功能,能讓程式碼寫起來更簡潔又快速,在使用上有些地方要特別留意。

js
document.querySelector('#Btn').addEventListener('mouseenter', () => {
  // Window
  console.log(this);
});

TIP

  • 箭頭函式沒有自己的 this。因此,在箭頭函式內使用 this 會指向最外層的 Window
  • 呈上,在 DOM 事件處理函式中,會找不到該 DOM 元素。因此,須改由 事件物件 來獲取 DOM。