I'm trying to understand how prototypal inheritance works when using constructor functions in Javascript. Take the following code for example:
let Animal = function (name, species, birthYear) {
this.name = name;
this.species = species;
this.birthYear = birthYear;
};
let spike = new Animal(`Spike`, `Dog`, 2000);
Animal.prototype.calculateAge = function () {
let age = 2022 - this.birthYear;
return age;
};
Animal.prototype.color = `brown`;
spike.calculateAge();
console.log(spike.color);
console.log(spike);
These last three lines are what I'm struggling to understand. Please let me know if my understanding is misguided at any point in my explanation.
I can call the calculateAge() method on the spike object because it inherited the method from the Animal prototype. Similarly, I can log spikes color property to the console because the spike object inherited the color property from the Animal prototype. When I inspect the spike object using console.log(), it has the properties of name, species, and birthYear that I defined, but there is also a prototype. Does this mean that the spike object contains the prototype, or is this simply identifying the prototype from which it inherited the aforementioned method and property? Also, I don't really feel like I understand what this Animal prototype is. I get that the code works and that's all well and good, but just what in the world is this Animal prototype thing? Is it its own object in and of itself?
Thank you for any explanation you can offer.