JavaScript - Symbol.species 屬性



為了指示應該使用哪個建構函式來建立派生物件,JavaScript 有一個獨特的屬性叫做 Symbol.species。在建立類的新的例項或物件時,此符號用作類或物件原型中的鍵,以標識要使用的建構函式。

Symbol.species 屬性允許使用者指定應該使用哪個建構函式來建立類或子類的新的例項。

語法

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

[Symbol.species]

引數

species 訪問器屬性用於允許子類覆蓋預設建構函式。

返回值

此屬性返回一個派生物件。

示例

示例 1

讓我們看下面的例子,我們將使用 map() 方法。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x extends Array {
            static get[Symbol.species]() {
               return Array;
            }
         }
         const a = new x(11, 2, 33);
         const b = a.map(x => x * 2);
         document.write(b instanceof x, " < br > "); 
            document.write(b instanceof Array);
      </script>
   </body>
</html>

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

示例 2

考慮下面的例子,我們將使用 slice() 方法。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x extends Uint8Array {
            static get[Symbol.species]() {
               return Uint8Array;
            }
         }
         const a = new x([11, 22, 33, 44]);
         const b = a.slice(1, 2);
         document.write(b instanceof x, " < br > ");
         document.write(b instanceof Uint8Array);
      </script>
   </body>
</html>

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

示例 3

在下面的示例中,我們將建立一個子類,並在子類的例項上使用 then() 方法。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x extends Promise {
            static get[Symbol.species]() {
               return Promise;
            }
         }
         const a = new x((resolve, reject) => {
            resolve('welcome');
         });
         const b = a.then(result => result.toUpperCase());
         document.write(b instanceof x, " < br > "); 
         document.write(b instanceof Promise);
      </script>
   </body>
</html>

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

廣告