Sub-classes are what make inheritance possible, which is one of the core aspects of the OOP paradigm. This allows us to maintain the behavior of one object in another without the need to do the same work again.
So how does sub-classing work? Let's show with code:
Here we want to maintain the employee properties in developer without duplication, so we created an inheritance manually using
employeeCreator as the parent class and
developerCreator as a sub-class.
We achieve this by creating a new employee with the
employeeCreator, then we extend this employee object with developer functionalities using the method
setPrototypeOf, then we can access any developer attributes from the employee object, and with the help of object.setPrototypeOf which let us have access to another object properties by getting it's
prototype and with this we can get the
sayName into the
developerFunctions and all of this in the
As you can see, some things changed. Now we can use the
new keyword to create a new object (instead of using
Object.create) and we also can call the constructor function
Employee to initialize its properties and add functions to
Developer we use call (instead of
Object.setPrototypeOf) to use the parent constructor on this new object we're creating, and after that, we add a
language value to
this. To keep up with
Employee functionalities, we pass its prototype to
Developer.prototype by creating an object with it.
Now we're using the ES2015 approach, as I said in my class article the class solution is just syntactic sugar to the last solution and works in the same way, but it's cleaner and easier to read if compared to the others.
this keyword is uninitialized, so we must call
super (which replaces the
Object.call) before we call
this. This happens because our object is only later instanced and returned in the
Employee to be automatically assigned to
this in the
Developer, so we can't just call
this at this point, but only after the
super. It's something like
this = super(name).
But how does
super knows it needs to run
Employee? It's just because of the
extends keyword, which replaces the need to add functions "behind the scenes", directly in the
prototype. Also, it sets a reference to the
Employee constructor in the
__proto__ in a property on
Objects that points to the
prototype set in them.
And that's the
class approach. This is what makes it possible to emulate an object-oriented language with a prototype-based environment.
Thanks for reading, if you want to improve your knowledge from here you can check the references for more.
We want to work with you! Check out our "What We Do" page.