• JavaScript Video Tutorials

JavaScript - Symbol.species Property



In order to indicate which constructor function should be used to create derived objects, JavaScript has a unique property called Symbol.species. When making new instances of a class or object, this symbol is used as a key in a class or object prototype to identify which constructor is to be used.

The Symbol.species property allow the users to specify which constructor function should be used to create new instances of a class or subclass.

Syntax

Following is the syntax of JavaScript Symbol.species property −

[Symbol.species]

Parameters

The species accessor property is used to allow subclasses to override the default constructor.

Return value

This property returns an derived object.

Examples

Example 1

Let's look at the following example, where we are going to use the map() method.

<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>

If we execute the above program, it will displays the text on the webpage.

Example 2

Consider the following example, where we are going to use the slice() method.

<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>

On executing the above script, it will displays a text on the webpage.

Example 3

In the following example, we are going to create a subclass and using the then() method on the instance of subclass.

<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>

When we execute the script, it will displays a text on the webpage.

Advertisements