Managing Instance Types

Learn about the instance type of an instance created by the base class method in JavaScript.

Suppose a method of your class, clone() for example, creates and returns an instance of its own type. Now, suppose you inherit from this class. A user of your derived class can automatically reuse the clone() method defined in its base class. However, when called on an instance of the derived class, should clone() return an object of the base type or the derived type?

In general, when using inheritance, if a method in the base class creates an instance, should that instance be of the base type or the derived type? 🤔

It’s a mark of an educated mind to say, “It depends!”

Sure, it may depend on the context, the application, and maybe several other things, but at the programming level, we need to have a way to manage the type of instance that’s created. First, we’ll take a look at how some built-in classes deal with this, and then we’ll focus on creating similar behavior for our own code.

Two built-in classes, different behaviors

Let’s take a look at two classes in JavaScript that implement the same method but with two different behaviors.

Get hands-on with 1200+ tech skills courses.