JavaScript - Reflect 物件



JavaScript Reflect

在 JavaScript 中,Reflect 是一個全域性物件,並在 ECMAScript 6 (ES6) 中引入。它包含靜態方法,提供了一種更好的方式在執行時與物件進行互動。

與大多數全域性物件不同,Reflect 不是建構函式。您不能使用 new 運算子或將 Reflect 物件作為函式呼叫。Reflect 的所有方法都是靜態的,就像 Math 物件一樣。

它包含各種方法,可以在執行時訪問、更新、刪除等物件的屬性。

Reflect 物件的關鍵特性

  • 物件構造 - Reflect API 允許使用 Reflect.construct() 方法在執行時建立物件。

  • 函式呼叫 - Reflect API 的 apply() 方法用於透過傳遞上下文和引數來呼叫函式或物件方法。

  • 物件屬性操作 - Reflect API 具有不同的方法來設定、更新或刪除物件屬性。此外,它還可以透過阻止它來處理物件的擴充套件。

語法

以下是使用 Reflect API 方法的語法:

Reflect.method();

在上述語法中,“method”是泛化。它可以是 Reflect API 的任何方法,例如 get、set、apply、construct、has 等。

Reflect 方法

在下表中,我們列出了 Reflect 的所有方法:

序號

名稱和描述

1

apply()

呼叫函式。

2

construct()

允許指定不同的原型。

3

defineProperty()

允許插入或編輯物件屬性。

4

deleteProperty()

允許刪除物件屬性。

5

get()

獲取屬性的值。

6

getOwnPropertyDescriptor()

允許獲取物件的描述符。

7

getPrototypeOf()

獲取物件的原型。

8

has()

檢查屬性是否存在於物件中。

9

isExtensible()

檢查物件是否可擴充套件。

10

ownKeys()

返回目標物件自己的鍵,並忽略繼承的鍵。

11

preventExtensions()

阻止物件的擴充套件。

12

set()

將值設定為物件屬性。

13

setPrototypeOf()

允許將物件的原型設定為 null 或另一個物件。

示例

示例 1

在下面的示例中,我們定義了一個 car 物件。“prop”變數以字串格式包含屬性名稱。

我們使用 Reflect 物件的 get() 方法從 car 物件訪問“model”屬性。我們將物件名稱作為 get() 方法的第一個引數,將屬性名稱作為第二個引數傳遞。

在輸出中,您可以看到“model”屬性的值。

<html>
   <body>
      <div id="output">The model of the car is: </div>
      <script>
         const car = {
            name: "Audi",
            model: "Q6",
            price: 7000000,
         }
         let prop = "model";
         let model = Reflect.get(car, prop);
         document.getElementById("output").innerHTML += model;
      </script>
   </body>
</html>

輸出

The model of the car is: Q6

示例 2

在下面的示例中,我們使用了 `set()` 方法將屬性設定到物件中。`set()` 方法接受物件、屬性名稱和值作為引數。

輸出顯示了 'doors' 屬性的值。透過這種方式,您可以使用 Reflect API 的 `set()` 方法在執行時將屬性設定到物件中。

<html>
   <body>
      <div id="output">The total doors in the Audi Q6 is: </div>
      <script>
         const car = {
            name: "Audi",
            model: "Q6",
            price: 7000000,
         }
         const model = Reflect.set(car, "doors", 4);
         document.getElementById("output").innerHTML += car.doors;
      </script>
   </body>
</html>

輸出

The total doors in the Audi Q6 is: 4

執行上述指令碼後,輸出視窗將彈出,並在網頁上顯示文字。

示例 3

在下面的示例中,我們使用了 `has()` 方法來動態檢查某個屬性是否存在於物件中。

這兩個符號看起來相似,但實際上是不同的,您可以在輸出中看到這一點。

<html>
   <body>
      <p id="output"></p>
      <script>
         const car = {
            name: "Audi",
            model: "Q6",
            price: 7000000,
         }
         const isName = Reflect.has(car, "name");
         if (isName) {
            document.getElementById("output").innerHTML = "The Car object contains the name.";
         }
      </script>
   </body>
</html>

輸出

The Car object contains the name.
廣告