JavaScript - Reflect.setPrototypeOf() 方法



Reflect.setPrototypeOf() 方法允許您設定物件的原型。它是 Reflect API 的一部分,Reflect API 提供了許多用於執行超程式設計任務的靜態方法,例如屬性操作和屬性操作的攔截。

如果您想修改現有物件的原型,可以使用 Reflect.setPrototypeOf() 方法。這在您想要建立一個從特定原型繼承的物件或想要擴充套件或修改物件行為的情況下非常有用。

語法

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

Reflect.setPrototypeOf(target, prototype)

引數

此方法接受兩個引數。下面描述了這些引數:

  • target - 要在其上設定屬性的物件。

  • prototype - 包含物件新原型的物件。它可以是任何物件或 null。

返回值

此方法返回一個布林值,指示原型是否成功設定。

示例

示例 1

讓我們看下面的例子,我們將設定一個物件的原型。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {};
         const y = {
            a: 10
         };
         Reflect.setPrototypeOf(x, y);
         document.write(x.a);
      </script>
   </body>
</html>

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

示例 2

考慮另一種情況,我們將更改現有物件的原型。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            a: 22
         };
         const y = {
            b: 123
         };
         Reflect.setPrototypeOf(x, y);
         document.write(x.b);
      </script>
   </body>
</html>

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

示例 3

在下面的示例中,我們將原型設定為 null。

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

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

示例 4

以下是示例,我們將檢查物件是否從原型繼承。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         let x = {
            a: 11
         };
         let y = {};
         Reflect.setPrototypeOf(y, x);
         document.write(Reflect.getPrototypeOf(y) === x);
      </script>
   </body>
</html>

執行上述指令碼後,它將生成一個輸出,其中包含顯示在網頁上的文字。

廣告