Map[Symbol.species]
The Map[Symbol.species]
static accessor property returns the constructor function that is used to create derived objects. By default, it returns the Map
constructor itself, allowing subclasses to override this behavior when creating derived instances.
Syntax
</>
Copy
Map[Symbol.species]
Return Value
Returns the constructor function used to create derived objects. By default, this is the Map
constructor itself:
</>
Copy
class MyMap extends Map {}
console.log(MyMap[Symbol.species]); // function Map()
Examples
1. Default Behavior of Map[Symbol.species]
By default, Map[Symbol.species]
returns the Map
constructor.
</>
Copy
console.log(Map[Symbol.species]);
Output
[Function: Map]
2. Overriding Symbol.species in a Subclass
Subclasses can override Symbol.species
to change the constructor used for derived objects.
</>
Copy
class CustomMap extends Map {
static get [Symbol.species]() {
return Map; // Ensures derived instances are of type Map
}
}
const myMap = new CustomMap();
const derived = myMap.set('key', 'value');
console.log(derived instanceof CustomMap); // true
console.log(derived instanceof Map); // true
Output
true
true
3. Changing Derived Object Constructor
This example demonstrates changing the constructor used for derived objects.
</>
Copy
class CustomMap extends Map {
static get [Symbol.species]() {
return null; // Prevents automatic instantiation
}
}
console.log(CustomMap[Symbol.species]); // null
Output
null
Setting Symbol.species
to null
means no new instances are created automatically when a method like map.set()
is called.