07. Species Pattern
Sometimes a method creates new instances of its class. If you create a subclass – should the method return an instance of its class or an instance of the subclass? A few built-in ES6 methods let you configure how they create instances via the so-called species pattern.
The standard species pattern is used by Promise.prototype.then()
, the filter()
method of Typed Arrays and other operations. It works as follows:
If
this.constructor[Symbol.species]
exists, use it as a constructor for the new instance.Otherwise, use a default constructor (e.g.
Array
forArrays
).
Implemented in JavaScript, the pattern would look like this:
Symbol.species
Symbol.species
This is the default getter for the property [Symbol.species]
:
You can override the default species via a static getter (line A):
As a result, map()
returns an instance of Array
:
If you don’t override the default species, map()
returns an instance of the subclass:
Last updated
Was this helpful?