JavaScript - Reflect.get() 方法



Reflect.get() 方法是 Reflect API 的一部分,該 API 提供了一組靜態方法,用於對物件執行類似於運算子執行的操作。此方法用於檢索物件的屬性值,類似於點運算子或括號表示法,但具有其他功能和靈活性。

語法

以下是 JavaScript Reflect.get() 方法的語法:

Reflect.get(target, propertyKey, receiver) 

引數

此方法接受三個引數。如下所述:

  • target - 要獲取其屬性的目標物件。

  • propertyKey - 要獲取的屬性的名稱。

  • receiver - 這是一個可選引數,它是為對 target 的呼叫提供的“this”的值。

返回值

此方法返回屬性的值。

示例

示例 1

讓我們看看下面的示例,我們將使用 Reflect.get() 並檢索屬性的值。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            car: 'Maserati',
            model: 2024
         };
         const y = Reflect.get(x, 'car');
         document.write(JSON.stringify(y));
      </script>
   </body>
</html>

如果我們執行上述程式,它將在網頁上顯示文字。

示例 2

考慮另一種情況,我們將使用 Reflect.get() 訪問使用符號定義的屬性。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = Symbol('tp');
         const y = {
            [x]: 'TutorialsPoint'
         };
         const z = Reflect.get(y, x);
         document.write(z);
      </script>
   </body>
</html>

執行上述指令碼後,它將在網頁上顯示文字。

示例 3

在下面的示例中,我們將訪問不存在的屬性並檢查輸出。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            state: 'Telangana',
            capital: 'Hyderabad'
         };
         const y = Reflect.get(x, 'population');
         document.write(y);
      </script>
   </body>
</html>

當我們執行上述指令碼時,輸出視窗將彈出,在網頁上顯示文字。

廣告