JavaScript - this關鍵字



什麼是 'this' 關鍵字?

在 JavaScript 中,'this' 關鍵字包含對物件的引用。它表示函式或當前程式碼的上下文。它用於訪問當前物件的屬性和方法。

當在函式內部使用 this 關鍵字時,this 將引用呼叫該函式的物件。

在 JavaScript 中,函式也是物件。因此,您也可以將 'this' 關鍵字與函式一起使用。

'this' 指的是哪個物件?

'this' 關鍵字引用的物件取決於您如何使用 'this' 關鍵字。

例如:

  • 'this' 關鍵字在全域性作用域中引用 window 物件。

  • 當您在函式內部使用 'this' 關鍵字時,它也表示 'window' 物件。

  • 在函式的嚴格模式下,'this' 關鍵字引用 undefined。

  • 當您在物件方法中使用它時,'this' 關鍵字引用該物件。

  • 在事件處理程式中,'this' 關鍵字引用執行該事件的元素。

  • 在 call()、apply() 和 bind() 等方法中的 'this' 關鍵字可以引用不同的物件。

語法

遵循以下語法在 JavaScript 中使用 'this' 關鍵字:

this.property
OR
this.method();

您可以使用 'this' 關鍵字訪問屬性並執行物件的方法。

JavaScript 中全域性作用域的 'this'

當您在全域性作用域中使用 'this' 關鍵字時,它表示全域性 (window) 物件。您可以使用全域性作用域中的 'this' 關鍵字訪問全域性變數。

示例

在下面的程式碼中,我們在全域性作用域中定義了 'num' 變數和 printNum() 函式。之後,我們使用 'this' 關鍵字訪問全域性變數和函式。

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById('demo');
      var num = 10;
      function printNum() {
         output.innerHTML += "Inside the function: " + num + "<br>";
      }
      this.printNum();
      output.innerHTML += "Outside the function: " + this.num + "<br>";
   </script>
</body>
</html>

輸出

Inside the function: 10
Outside the function: 10

JavaScript 函式中的 'this'

當您在函式中使用 'this' 關鍵字時,它表示全域性作用域或 'window' 物件。

示例

在下面的程式碼中,我們在函式內部使用了 'this' 關鍵字。您可以觀察到我們使用函式內部的 'this' 關鍵字訪問全域性變數。

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById('demo');
      var message = "Hello World!";
      function printMessage() {
         var message = "Hi! How are you?";
         output.innerHTML = "The messsage is: " + this.message;
      }
      printMessage();
   </script>
</body>
</html>

輸出

The messsage is: Hello World!

嚴格模式下函式中的 'this'

當您在嚴格模式下的函式內部使用 'this' 關鍵字時,它不引用任何物件。'this' 關鍵字的值變為 undefined。

示例

在下面的程式碼中,我們在嚴格模式下的函式內部使用了 'this' 關鍵字。它列印 undefined。

<html>
<body>
   <div id = "demo"> </div>
   <script>
      let output = document.getElementById('demo');
      var message = "Hello World!";
      function test() {
         "use strict";
         output.innerHTML = "The value of this in the strict mode is: " + this;
      }
      test();
   </script>
</body>
</html>

輸出

The value of this in the strict mode is: undefined

建構函式中的 'this'

當您將函式用作建構函式來建立物件時,'this' 關鍵字引用該物件。

示例

我們在下面的程式碼中定義了 Animal() 建構函式。我們在建構函式內部使用了 'this' 關鍵字來初始化物件的屬性。

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById('demo');
      function Animal() {
         this.name = 'Lion';
         this.age = 3;
         this.color = 'Brown';
      }
      const newAnimal = new Animal();
      output.innerHTML = "Animal Name: " + newAnimal.name + "<br>";
      output.innerHTML += "Animal Age: " + newAnimal.age + "<br>";
      output.innerHTML += "Animal Color: " + newAnimal.color; 
   </script>
</body>
</html>

輸出

Animal Name: Lion
Animal Age: 3
Animal Color: Brown

箭頭函式中的 'this'

當您在箭頭函式中使用 'this' 關鍵字時,它引用其父物件的範圍。

例如,當您在物件方法內部定義箭頭函式並在其中使用 'this' 關鍵字時,它表示該物件。如果您在另一個函式內部定義箭頭函式,則 'this' 關鍵字引用全域性物件。

示例

在下面的程式碼中,我們在物件的 getDetails() 方法內部定義了箭頭函式。當我們列印 'this' 關鍵字的值時,它列印該物件。

<html>
<body>
   <div id = "output1">Value of 'this' inside the getDetails() method: </div>
   <div id = "output2">Value of 'this' inside the getInnerDetails() method: </div>
   <script>
      const wall = {
		 size: "10",
		 color: "blue",
		 getDetails() {
		    document.getElementById('output1').innerHTML += JSON.stringify(this);
			const getInnerDetails = () => {
			   document.getElementById('output2').innerHTML += JSON.stringify(this);
			}
			getInnerDetails();
	     }
      }
      wall.getDetails();
   </script>
</body>
</html>

輸出

Value of 'this' inside the getDetails() method: {"size":"10","color":"blue"}
Value of 'this' inside the getInnerDetails() method: {"size":"10","color":"blue"}

物件方法中的 'this'

當您在物件方法內部使用 'this' 關鍵字時,它表示物件本身。

示例

在下面的程式碼中,我們定義了 'fruit' 物件。該物件包含 printFruitDetails() 方法,在該方法中,我們使用了 'this' 關鍵字來訪問物件的屬性。

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById('demo');
      const fruit = {
         name: "Apple",
         color: "red",
         printFruitDetails() {
            output.innerHTML += "Furit Name = " + this.name + "<br>";
            output.innerHTML += "Fruit Color = " + this.color;
         }
      }
      fruit.printFruitDetails();
   </script>
</body>
</html>

輸出

Furit Name = Apple
Fruit Color = red

物件方法的子函式中的 'this'

當您在物件方法內部定義函式並在該函式內部使用 'this' 關鍵字時,它表示全域性物件而不是物件。

示例

在下方的程式碼中,我們定義了 person 物件。person 物件包含 printDetails() 方法。在 printDetails() 方法中,我們定義了 printThis() 函式。

在 printThis() 函式中,我們列印了“this”關鍵字的值,它列印的是全域性物件。

<html>
<body>
<div id = "output">Inside the printThis() function, Value of 'this' =  </div>
<script>
   const person = {
      name: "Salman",
      isBusinessman: false,
      printDetails() {
         function printThis() {
            document.getElementById('output').innerHTML += this;
         }
         printThis();
      }
   }
   person.printDetails();
</script>
</body>
</html>

輸出

Inside the printThis() function, Value of 'this' = [object Window]

JavaScript 中事件處理程式中的“this”

在事件處理程式中使用“this”關鍵字指的是執行事件的 HTML 元素。

示例

在下方的程式碼中,我們在 <div> 元素中添加了 onClick 事件處理程式。當用戶點選 div 元素時,我們使用“display”屬性隱藏 div 元素。

<html>
  <head>
    <style>
      div {
        height: 200px;
        width: 700px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <p>Click the DIV below to remove it. </p>
    <div onclick = "this.style.display = 'none'"> </div>
  </body>
</html>

JavaScript 中的顯式函式繫結

在 JavaScript 中,call()、apply() 或 bind() 方法用於顯式繫結。

顯式繫結允許你借用特定物件的的方法。使用這些方法,你可以顯式地定義“this”關鍵字的上下文。

讓我們透過下面的例子來理解顯式繫結。

示例:使用 call() 方法

在下方的程式碼中,lion 物件包含 color 和 age 屬性。它還包含 printDetails() 方法,並使用“this”關鍵字列印詳細資訊。

tiger 物件只包含 color 和 age 屬性。我們使用 call() 方法來呼叫 lion 物件的 printDetails() 方法,並使用 tiger 物件作為上下文。因此,該方法會輸出 tiger 的詳細資訊。

<html>
<body>
<div id = "demo"> </div>
<script>
  const output = document.getElementById('demo');
  const lion = {
    color: "Yellow",
    age: 10,
    printDetails() {
      output.innerHTML += `<p>Color: ${this.color}</p>`;
      output.innerHTML += `<p>Age: ${this.age}</p>`;
    }
  }
  const tiger = {
    color: "Orange",
    age: 15,
  }
  lion.printDetails.call(tiger);
</script>
</body>
</html>

輸出

Color: Orange

Age: 15

示例:使用 bind() 方法

下面的程式碼也包含 lion 和 tiger 物件。之後,我們使用 bind() 方法將 lion 物件的 printDetails() 方法繫結到 tiger 物件。

之後,我們使用 tigerDetails() 方法列印 tiger 物件的詳細資訊。

<html>
<body>
<div id = "demo"> </div>
<script>
  const output = document.getElementById('demo');
  const lion = {
    color: "Yellow",
    age: 10,
    printDetails() {
      output.innerHTML += `<p>Color: ${this.color}</p>`;
      output.innerHTML += `<p>Age: ${this.age}</p>`;
    }
  }
  const tiger = {
    color: "Orange",
    age: 15,
  }
  const tigerDetails = lion.printDetails.bind(tiger);
  tigerDetails();
</script>
</body>
</html>

輸出

Color: Orange

Age: 15

JavaScript “this” 的優先順序

你應該使用以下優先順序順序來確定“this”關鍵字的上下文。

  • 1. bind() 方法
  • 2. call 和 apply() 方法
  • 3. 物件方法
  • 4. 全域性作用域
廣告