The Prototype
is the mechanism by which all JavaScript objects inherit from one another. You can think of the prototype as an object that objects use to hold onto values that can be passed down to other objects. We use it all the time in inheritance.
Example:
function Person(attributes) {
this.age = attributes.age;
this.name = attributes.name;
this.homeTown = attributes.homeTown;
}
Person.prototype.speak = function () {
return `Hello, my name is ${this.name}`;
};
Let’s look at how inheritance works with prototypes. Here we create a Child
constructor. Notice we are using the .call()
method to bind this
to Person
.
Inheritance .call()
Example:
function Child(childAttributes) {
Person.call(this, childAttributes); // binding this to Person
this.isChild = childAttributes.isChild; // this will be a special attribute to Child
}
The problem with Child
is that it doesn’t necessarily know about the Person
prototype
yet. We have to manually tell Child
about Person
using Object.create()
.
Example:
Child.prototype = Object.create(Person.prototype);
.call()
?Allows you to write a method, or function that can be used on different objects.
Example: