Prototypes
A prototype is the mechanism in JavaScript that makes it possible to have objects. When nothing is specified when creating a class, the objects inherit from the Object.prototype
prototype. This is a rather complex built-in JavaScript class that we can use. We don't need to look at how this is implemented in JavaScript, as we can consider it the base object that is always on top of the inheritance tree and therefore always present in our objects.
There is a prototype
property available on all classes, and it is always named "prototype." We can access it like this:
ClassName.prototype
Let's give an example of how to add a function to a class using the prototype
property. In order to do so, we'll be using this Person
class:
class Person {
constructor(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
greet() {
console.log("Hi there!");
}
}
And here is how to add a function...