Well, let us look at another example:
// Prior to ES6, JavaScript had no 'class' keyword, so you
// can think of the following implementation of a function
// as a class.
function Human(name) {
this.name = name;
this.species = 'Mammal';
this.likesFood = function() {
return true;
}
}
// Now, I create some new instances of Human:
const nerdifico = new Human('Nerdifico');
const sky = new Human('Sky');
nerdifico.likesFood() // refers to nerdifico's function
sky.likesFood() // refers to sky's function
Now, in memory, we each have our own name
and species
property (even if the value is the same). Importantly, we each have our own likesFood
function. However, this is not scalable, best-practice, nor necessary.
We can create a prototype
associated with the base class (technically, function) so that it is not a unique function for each and every new
(important) instance, but is a universal function:
function Human(name) {
this.name = name;
this.species = 'Mammal';
}
Human.prototype.likesFood = function() {
return true;
}
const nerdifico = new Human('Nerdifico');
const sky = new Human('Sky');
nerdifico.likesFood() // refers to Human's method
sky.likesFood() // refers to Human's method
Please understand: This is simplified, as I do not have an internal understanding of JavaScript’s working.
I hope this helps, though…
P.S. What helped me a lot with understanding this
, prototype
, class
, the general OOP principles possible in JS, was a channel on YouTube called The Coding Train. The owner does some brilliant Coding Challenges where he often makes use of this.