Okay, we first need to discuss the concept of a class and instances of that class. Let’s say you and I both worked at that company from my earlier reply. We would both be instances of the Employee
class. We would both have properties in common, but the values can be different. For example:
vipatron = new Employee();
vipatron.name = "Vip";
vipatron.address = "Philadelphia";
vipatron.EmployeeID= "11111";
SMGeorg = new Employee();
SMGeorg.name = "Egor";
SMGeorg.address = "St. Petersburg";
SMGeorg .EmployeeID= "22222";
Let’s start with the second line of code:
let terrier = Object.create(Animal.prototype);
In this case, terrier
is an instance of Animal. It has whatever properties and methods an Animal
had. It would be as if you wrote:
let terrier = new Animal();
On the other hand, there is some code that’s missing from your first line of code:
/* Missing Code Below*/
function Dog () {
this.soundMade = "woof!"
}
/* End of Missing Code*/
Dog.prototype = Object.create(Animal.prototype);
What’s going on is that we are first declaring the Dog
function. If we were to write myDog = new Dog()
, myDog
would be an object of type Dog
because we used the new
operator. If we accessed myDog.soundMade
, it would return "woof!"
.
By virtue of functions in Javascript being full Javascript Objects (they inherit from the Object class), they have properties. One of those properties is called prototype
. By assigning Dog.prototype
to an instance of the Animal
class, whenever an instance of Dog
is created (by Object.create(Dog.prototype)
or new Dog()
), Javascript looks at Dog.prototype
and says: okay, there is a specific instance of Animal from which we are copying our new
Dog object. The fact that a subclass’ prototype is an instance of the superclass’ prototype means that after making the subclass prototype assignment, we can then add more properties to the prototype of the subclass, for example:
Dog.prototype.constructor = Dog;
Dog.prototype.showHappiness = function (){ console.log("wagging tail...") };
myInheritedDog = new Dog();
myInheritedDog.eat(); //inherited from Animal
myInheritedDog.showHappiness();
The console should show two lines:
nom nom nom
wagging tail...