Intro
In JavaScript, a prototype is a hidden property on an object that references an object or is set to null. If the script runs and can’t find a property/method in the targeted object. It then checks to see if the prototype could potentially have the property/method. In the following examples I will demonstrate how prototype delegation works.
The Prototype
Here I will set car to be the prototype of different types of cars. We can use car to behave as a storage of many different methods but in this case we will have an accelerate method that will print to the console how fast a particular car accelerates. The keyword this will refer to the object that's at the left of the dot at call time.
Prototypal inheritance
To use the accelerate method on the hellCat object you have to set hellCat's prototype to car. A way to accomplish this is to create a property with the key as two underscores on each side of the word proto and the value the desired object. Car is now the parent to the hellcat object! When accelerate gets invoked with hellCat to the left of the dot, the script will run to see that it does not have the method inside hellCat. Since car is set to the prototype. Hellcat inherits the accelerate method so "Hellcat accelerates 0 to 60 in 3.6 seconds" gets printed to the console.
Prototype chain
Here Zr1's prototype is set to hellcat. When the script runs it will see that the accelerate method is not in Zr1. Although, Zr1 did inherit hellCat's characteristics. Which hellCat inherited characteristics from car object. This demonstrates the script going up the prototype chain until it finds the method in car.
I hope I could help you understand how prototype delegation works. This is also a form of prototypal inheritance which some programmers might not agree with. Maybe I'll post on that but until next time thanks for reading! Peace!
Top comments (0)