Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript this Keyword ความหมายและการใช้งาน

this ใน JavaScript อ้างอิง Object ที่เรียก Function นั้น ค่าขึ้นอยู่กับ วิธีการเรียกใช้ (Runtime Binding)

ตัวอย่าง

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>this Keyword</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 to see what 'this' refers to in different contexts </h3>
  <script>
    let sampleEle = document.querySelector(".sample");
    
    function test() { return this; }
    
    let testObj = {
      a: 22,
      check() { return this; }
    };
    
    document.querySelector(".Btn").addEventListener("click", () => {
      sampleEle.innerHTML = "this in global scope = " + this + "<br>";
      sampleEle.innerHTML += "this in normal function = " + test() + "<br>";
      sampleEle.innerHTML += "this in method = " + testObj.check() + "<br>";
      sampleEle.innerHTML += "this in arrow function = " + (() => this)() + "<br>";
    });
  </script>
</body>
</html>

กฎของ this (4 กรณีหลัก)

  1. Global/Function โดด: this = Window (Strict Mode = undefined)
  2. Method ของ Object: this = Object นั้น (testObj)
  3. Constructor (new): this = Instance ใหม่
  4. call/apply/bind: this = Argument แรกที่ส่งเข้าไป

Arrow Function

Arrow Function ไม่มี this ของตัวเอง ใช้ this ของ Lexical Scope (Scope ที่ประกาศ)

ผลลัพธ์

แสดง this ในบริบทต่างๆ: Global=Window, Function=Window, Method=testObj, Arrow=Window