JavaScript - Reflect.getPrototypeOf() 方法



Reflect.getPrototypeOf() 方法用於返回物件的原型。它類似於 Object.getPrototypeOf() 方法,但它是 Reflect 物件的一部分,Reflect 物件提供了一組用於對物件執行元操作的方法。

使用 Reflect.getPrototypeOf() 方法的主要優點是它可以與 Proxy API 結合使用。它可以幫助你攔截和修改物件的操作,包括原型的檢索。此方法為 JavaScript 操作提供了反射 API,增強了該語言的自省功能。

語法

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

Reflect.getPrototypeOf(obj)

引數

此方法僅接受一個引數。下面介紹了這些引數:

  • obj - 你想要檢索其原型的物件。

返回值

此方法返回給定物件的原型。

示例

示例 1

讓我們看下面的例子,我們將使用 Reflect.getPrototypeOf() 來檢索空物件的原型。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {};
         const prototype = Reflect.getPrototypeOf(x);
         document.write(prototype);
      </script>
   </body>
</html>

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

示例 2

考慮另一種情況,我們將使用物件字面量並建立一個物件。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         let x = {
            car: 'RS6'
         };
         document.write(Reflect.getPrototypeOf(x) === Object.prototype);
      </script>
   </body>
</html>

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

示例 3

在下面的示例中,我們將獲取陣列的原型。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = [11, 22, 33];
         const prototype = Reflect.getPrototypeOf(x);
         document.write(JSON.stringify(prototype));
      </script>
   </body>
</html>

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

廣告