JavaScript - Symbol.hasInstance 屬性



在 JavaScript 中,一個名為 Symbol.hasInstance 的唯一符號屬性使物件能夠指定當使用 instanceof 運算子時它們的行為方式。當 Symbol.hasInstance 作為物件上的方法指定時,它控制使用 instanceof 生成的例項在針對該物件進行測試時的行為。

透過使用此符號,使用者定義的物件可以自定義 instanceof 運算子的行為,從而在決定物件是否為特定建構函式的例項方面擁有更大的自由度。

語法

以下是 JavaScript Symbol.hasInstance 屬性的語法:

[Symbol.hasInstance](Object)

引數

此方法僅接受一個引數。下面描述了該引數:

  • object - 一個物件,它是建構函式之一。

返回值

如果該值位於物件的鏈中,則返回 true,否則返回 false。

示例

示例 1

讓我們來看下面的示例,我們將為自定義類自定義 instanceof。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x {
            static[Symbol.hasInstance](instance) {
               return Array.isArray(instance);
            }
         }
         const a = [11, 2, 33];
         document.write(a instanceof x);
      </script>
   </body>
</html>

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

示例 2

考慮另一種情況,我們將為自定義物件自定義 instanceof。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         function examp() {}
         const x = new examp();
         examp[Symbol.hasInstance] = function(instance) {
            return instance.constructor && instance.constructor.name === "TP";
         };
         document.write(x instanceof examp);
      </script>
   </body>
</html>

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

示例 3

在下面的示例中,我們將使用帶有 Symbol.hasInstance 屬性的自定義建構函式。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         function examp() {}
         examp[Symbol.hasInstance] = function(instance) {
            return instance instanceof examp && instance.isValid();
         };
         const x = new examp();
         document.write(x instanceof examp);
      </script>
   </body>
</html>

當我們執行指令碼時,它將在網頁上顯示文字。

示例 4

以下是示例,我們將使用帶有繼承的 Symbol.hasInstance。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x {
            static[Symbol.hasInstance](instance) {
               return 'dance' in instance && typeof instance.dance === 'function';
            }
         }
         class y {
            dance() {
               document.write("cat is dancing");
            }
         }
         let cat = new y();
         document.write(cat instanceof x);
      </script>
   </body>
</html>

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

廣告