Recently, I have been learning about inheritance and the prototype chain. If you have read my posts you already know I've been diving into the fundamentals of Javascript. You probably don't know I am a huge Hunter x Hunter fan as well. I put my learning about in practice by creating a Hunter prototype object.
Function Constructor
A function constructor can be seen as a blueprint for a particular type of object. The convention is to name a function constructor with a capital letter. For example, my function constructor is a blueprint to create Hunters.
I declare that all Hunters will take two parameters, a name
and hatsu
(or special power for those who aren't familiar). Each Hunter will be initialized with a powerLevel
of 100. Now let's add some abilities to our Hunters.
const Hunter = function(name, hatsu) {
this.name = name;
this.hatsu = hatsu;
this.powerLevel = 100;
};
Hunter.prototype.charge = function(number) {
if (typeof number !== 'number') {
console.log('Please enter a number');
return;
}
this.powerLevel += (100 * number);
console.log(this.name + ' power level at ' + this.powerLevel);
};
Hunter.prototype.useHatsu = function() {
if (this.powerLevel >= 300) {
console.log(this.name + ' used ' + this.hatsu);
this.powerLevel = 0;
} else {
console.log(this.name + ' needs to charge.');
};
};
By using the prototype
property to store the methods charge
and useHatsu
all future hunters will have the ability to charge up and use their powers. I could declare these functions in my constructor. That would mean each new Hunter created would have it's own charge
and useHatsu
method. That's a bit excessive, I don't need each Hunter to own the method I just need each Hunter to have access to it.
I save memory by creating the function once and allowing each Hunter to inherit these methods from the Hunter.prototype
property.
const gon = new Hunter("Gon", "Ja-Jan-Ken");
const killua = new Hunter("Killua", "Lightningbolt");
console.log(gon)
console.log(killua)
killua.charge(3);
gon.charge(1);
killua.useHatsu();
gon.useHatsu();
If you haven't entered the code into the console yet, go ahead and add it all. Take a look at the objects created. You'll notice they have their name
, hatsu
, and powerLevel
as expected. You may notice the function we created is not stored in the object. They are stored in its ___proto___
property.
We don't need to include the prototype
property in our function call because of the prototype chain. Similar to the scoping chain, javascript checks the object's own methods and properties. If nothing is found it checks the object's prototype. It continues this process until it reaches the top-level of the prototype chain which is null
.
I covered a lot of complicated topics in a very brief manner. If something doesn't make sense please reach out. This article by Tim Kadlec helped a lot.
Thanks for reading!
Top comments (0)