DEV Community

Wesley Schmidt
Wesley Schmidt

Posted on

Polymorphism and ES6

Polymorphism is a core concept of object-oriented programming or (OOP). It's what allows us to define not only the data type of a data structure, but also the types of operations that they use in javascript. Using this provides the use of the same method on different objects. With inheritance we can share these methods or override them.

Different types of inheritance include: Functional, Functional-shared, Prototypal, Pseudoclassical, and ES6. As an example we will be using ES6 as our preferred inheritance type. The first step is to create a super-class (or parent class) for our objects to inherit from. This is done using the class keyword and placing our desired variables in its constructor. for example:

As you can see we created a variable for our Robot's model, color, and job as well as creating an identification method that will return our model. Great, now that we can create a robot, lets get more specific. This is where sub-classes (or children) come in. We can create a child in ES6 using the extends keyword.

By using the super() method we can inherit variables and methods from our Robot class as well as create brand new ones. We can see polymorphism in action when altering these inherited properties!

To go one step further, we can create a sub-class of our sub-class (grandchildren if you will) to create additional customization using the same format.

Here, we can see that we can even overwrite methods to preform other actions under the same method names.

This is just another example of polymorphism!

So, in conclusion, ES6 is a great, easy way to create objects that share properties amongst one another. It saves memory and time by cutting down on the amount of typing that is necessary, while removing redundant code. This customization goes even further when using polymorphism to sculpt exactly what you want to be done!

Top comments (0)