Inheritance
Objective
To understand how to implement inheritance in JavaScript.
Prototypical Inheritance
Since JavaScript Objects don't have functionality copied over in inheritance, they use a term called prototypical inheritance, because inherited functionality is linked to the prototype chain. Let's look at an example.
Example Start
Since we've written this code a lot, you can just copy and paste the example code from the docs. Make sure to understand what the code is doing, notice the slight differences.
Only the properties are defined inside the constructor
Methods on the other hand, are all defined on the constructor's prototype. Here's the
greeting()
method:
Teacher()
Remember previously when we created a Teacher
class? It had a new property called subject
and a more formal greeting()
method didn't it? Let's figure out how to code it.
First, we'll define the constructor function.
A few things:
We've added the
call()
function. This allows theTeacher()
constructor to take thePerson()
constructor's parameters.The last line we added creates the
subject
property, because a generalPerson()
doesn't have a subject associated with it.We could have added a bunch of
this.
, for examplethis.age = age;
. This totally defeats the purpose of using inheritance and is more lines of code though.
(Unsure whether or not to add section on inheriting from constructor with no parameters)
Teacher()'s Prototype and Constructor Reference
Uh oh, we have a problem! Teacher()
doesn't have Person()
's methods yet! See for yourself by comparing Person.prototype.greeting
and Teacher.prototype.greeting
in your console window. (Instructor might ask, what do you see?)
Let's add some code so that it inherits the methods we've previously defined.
Hey, that create()
looks familiar! (Talk through what exactly it's doing?)
We'll need to add another bit of code as well, anyone know why? (We need to change Teacher.prototype's constructor property. It's currently equal to Person(). This is because Teacher.prototype is set to reference an object that inherits from Person.prototype.)
greeting() function
Our last step is to give the Teacher()
constructor a new greeting()
function. Here's the code you'll need:
Challenges and Such
Now that we have got it all set up, try to create an object instance of
Teacher()
. You can double check by trying to access your new object's properties and methods in the console.At the beginning of this gitbook, we also had a
Student
class. After looking back at it, try to replicate what we just did by implementing aStudent()
constructor.
Last updated