Here are our goals:
- What is a Prototype?
- What Datatypes have Prototypes?
- What do Prototypes give us?
- What is a Prototype Property?
- What is the proto property?
- How do functions and Prototypes work together?
Prototypes allow us to define methods or properties to all instances created of a particular object. Accordingly, every instance of that object has access to the method or property. This is huge because it saves time and DRYs our code since the method or property does not have to be defined in the Object constructor function or redefined for each instance of an object.
So far, we have learned that prototype properties allow us access to properties and/or methods. To continue to understand this, it is also important to note that all object constructors have a prototype property. And every object constructor has a prototype of "Object Prototype".
Let's take a look at an example:
this.name = name
This is a simple Object Constructor. From this, we can create an infinite amount of instances of "Person" each with a property of "name".
Now, why is this important? It is important because every instance of an object has a proto property that points to the Object Prototype of the constructor function that created said instance. And it is the proto property's job to look to the Object Prototype of the constructor to see if it has any methods or functions available to use.
The chain expedites searching to see if an instance of an object has access to certain methods; it simply uses this "formula":
Instance.__proto__ === Constructor.prototype
If the proto property of an instance is strictly equal to the constructor's prototype, then we know that the instance was instantiated from that object constructor.
You can also check this way:
console.log(Charlie.__proto__ === Person.prototype)
// the console should return 'true'
** Remember, I am still learning as well as you. Please feel free to leave comments, questions + suggestions below. Happy learning! **