JavaScript - Reflect.getOwnPropertyDescriptor() 方法



Reflect.getOwnPropertyDescriptor() 方法允許您檢索物件上給定屬性的屬性描述符。它提供了有關屬性的詳細資訊,例如其可配置性、可列舉性和可寫性。與 Object.getOwnPropertyDescriptor() 相比,此方法是 Reflect 物件的一部分,它提供了一種更靈活、更一致的方法來訪問屬性描述符。它在超程式設計場景中特別有用,可以實現動態屬性操作。

語法

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

Reflect.getOwnPropertyDescriptor(target, propertyKey)

引數

此方法接受兩個引數。具體如下:

  • target − 要檢索其屬性描述符的物件。

  • propertyKey − 要檢索其描述符的屬性名稱。

返回值

此方法返回物件上屬性的屬性描述符。如果屬性不存在,則返回 undefined。

示例

示例 1

讓我們看下面的例子,我們將從物件中檢索屬性 car 的屬性描述符。

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

如果執行上面的程式,它將在網頁上顯示文字。

示例 2

考慮另一種情況,我們將獲取一個不可列舉的屬性描述符。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         let x = {};
         Object.defineProperty(x, 'Tp', {
            value: 'Welcome',
            enumerable: false
         });
         let y = Reflect.getOwnPropertyDescriptor(x, 'Tp');
         document.write(JSON.stringify(y));
      </script>
   </body>
</html>

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

示例 3

在下面的示例中,我們將對不存在的屬性使用 Reflect.getOwnPropertyDescriptor() 方法。

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

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

廣告