JavaScript this 識別符號


JavaScript this 關鍵字引用它所屬的物件。如果單獨存在或在函式內部,它可以引用全域性物件。如果在方法內部,它引用所有者物件,在事件偵聽器中,它引用接收事件的 HTML 元素。

以下是 JavaScript this 識別符號的程式碼 −

示例

 即時演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>JavaScript this Identifier</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to see which object 'this' refers to in multiple
context
</h3>
<script>
   let thisRef = this;
   let sampleEle = document.querySelector(".sample");
   function test() {
      return this;
   }
   let testObj = {
      a: 22,
      check() {
         return this;
      },
   };
   document.querySelector(".Btn").addEventListener(
      "click",
      () => {
         sampleEle.innerHTML ="This inside normal function = " + test() + "<br>";
         sampleEle.innerHTML +="This inside a method = " + testObj.check() + "<br>";
         sampleEle.innerHTML += "This without any scope = " + thisRef + "<br>";
      },
      false
   );
</script>
</body>
</html>

輸出

點選“單擊此處”按鈕 −

更新於:2020 年 5 月 12 日

120 次檢視

開啟您的職業生涯

完成課程以獲得認證

開始
廣告