Introduction
This is a short post about inheritence in JavaScript.
While you read this post, take a moment to connect with me on LinkedIn.
Body
Not until ECMAScript 2015 had class syntax. Before that there was prototype inheritance
Suppose there is a function:
|
|
Now when you want to return the fullname, you can either define a function inside the FullName function only, like this;
|
|
This is obviously correct, but there is an overhead that every time the FullName entity is created, it creates the fullName function which kind of wastage of space. What if there was the main place where there was a fullName function defined? And all runtime variables would be defined to new objects?
This is where the prototype comes in. Below is how we would define a fullName prototype to the FullName entity.
|
|
Inheritence with protoypes
When you want to inherit from the FullName
object. This is what you would do:
|
|
What this tells the interpreter is that runs the constructor of the FullName
.
Wrong way for inheritance:
|
|
This will overwrite the FullName
.
Correct way to do this:
|
|
Key takeaways:
Everything in JavaScript is an object. Just like Python.