JavaScript - Reflect.has() 方法



Reflect.has() 方法用於確定目標物件是否具有特定屬性。它類似於 `Object.prototype.hasOwnProperty()` 方法或 `in` 運算子,但它提供了一種更靈活、更一致的執行屬性檢查的方法。`Reflect.has()` 方法不是函式,而是一個靜態方法,因此不應將其用作函式。

與 `Object.prototype.hasOwnProperty()` 相比,`Reflect.has()` 在目標物件為 null 或 undefined 時不會引發錯誤。在某些情況下,它會返回 false。

語法

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

Reflect.has(target, propertyKey)

引數

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

  • target − 要在其上獲取屬性的目標物件。

  • propertyKey − 要檢查的屬性名稱。

返回值

此方法返回一個布林值,指示目標物件是否具有該屬性。

示例

示例 1

讓我們來看下面的例子,我們將使用 Reflect.has() 來檢查物件是否具有屬性。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            car: 'BMW',
            Model: 2018
         };
         document.write(Reflect.has(x, 'Model') + " < br > ");
         document.write(Reflect.has(x, 'spare'));
      </script>
   </body>
</html>

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

示例 2

考慮另一種情況,我們將 configurable 設定為 false,嘗試刪除屬性並使用 Reflect.has() 獲取輸出。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {};
         Object.defineProperty(x, 'Bike', {
            value: 'Rx100',
            configurable: false
         });
         delete x.Bike;
         document.write(Reflect.has(x, 'Bike'));
      </script>
   </body>
</html>

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

示例 3

在下面的示例中,我們將使用 Reflect.has() 來檢查符號屬性是否存在。

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

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

示例 4

以下示例演示如何使用 Reflect.has() 檢查繼承屬性。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x {
            constructor() {
               this.a = 11;
            }
         }
         class y extends x {
            constructor() {
               super();
               this.b = 22;
            }
         }
         const z = new y();
         document.write(Reflect.has(z, 'a'));
      </script>
   </body>
</html>

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

廣告