Search⌘ K
AI Features

Solution Review: Instance Type

Explore how to handle instance types in JavaScript by using inheritance and the Symbol.species property. Understand how constructors in derived classes can control returned instances when methods like copy() are called, helping you write flexible and maintainable class-based code.

Solution

Let’s break down the solution to the challenge given in the previous lesson.

Javascript (babel-node)
'use strict';
class Base {
copy() {
const constructor =
Reflect.getPrototypeOf(this).constructor[Symbol.species] ||
Reflect.getPrototypeOf(this).constructor;
return new constructor();
}
}
class Derived1 extends Base {
static get [Symbol.species]() {
return Base;
}
}
class Derived2 extends Base {
static get [Symbol.species]() {
return Derived2;
}
}
const derived1 = new Derived1();
const derived2 = new Derived2();
console.log(derived1.copy()); //Base {}
console.log(derived2.copy()); //Derived2 {}

Explanation

As you know, you can change the behavior of an instance type by implementing the Symbol.species property getter in the derived class. So, we ...