JavaScript - Reflect.construct() 方法



Reflect.construct() 方法用於使用給定的引數集建立建構函式的例項。它是 Reflect 物件的一部分,該物件提供了一些用於操作物件及其屬性的靜態方法。當您需要動態構建建構函式的例項,而無需在編碼時知道建構函式的名稱時,Reflect.construct() 方法非常有用。

語法

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

Reflect.construct(target, argumentsList, newTarget)

引數

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

  • target − 目標函式的呼叫。

  • argumentsList − 一個類似陣列的物件,指定應使用哪些引數呼叫目標。

  • newTarget − 可選引數,用於指定要使用其原型的建構函式。

返回值

此方法返回目標的新例項。

示例

示例 1

讓我們來看下面的示例,我們將建立一個類的例項。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x {
            constructor(a) {
               this.a = a;
            }
         }
         const instance = Reflect.construct(x, ['WELCOME']);
         document.write(instance.a);
      </script>
   </body>
</html>

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

示例 2

考慮另一個場景,我們將使用陣列原型建立一個類的例項。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x {
            constructor(a) {
               this.a = a;
            }
         }
         const instance = Reflect.construct(x, ['TutorialsPoint'], Array);
         document.write(instance instanceof Array, " < br > "); 
               document.write(instance.a);
      </script>
   </body>
</html>

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

示例 3

在下面的示例中,我們將建立一個沒有任何引數的類的例項。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x {
            constructor() {
               this.Company = 'Maserati';
            }
         }
         const car = Reflect.construct(x, []);
         document.write(JSON.stringify(car));
      </script>
   </body>
</html>

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

廣告