Let me explain it to you in a few words and then show you some code for a better understanding.
Well date objects inherit from Date.prototype, array objects from Array.prototype and so on:
And all and i mean ALL objects inherit in the end from the object prototype. For example our array object you see above inherit from Array.prototype and this in turn inherit from object prototype.
Everything inside of the prototype can be called directly on the newly created Object. That is the reason why you can call myArray.push() or myArray.length. This way we dont have to overload our objects and put every method and every property on each instance of our object. We use prototypes for that!
Go ahead and copy the code you see above and see whats inside of proto to get a better understanding.
Let´s dive into some code. I encourage you after you read this article to grab this code and play with it. Thats the best way to learn and understand what prototype is and where and why to use it.
First we define a constructor:
You can see right now its an object which inherit from object prototype:
Here we use the prototype of our object to enhance it with a new method. You may noticed that inside of this new method we have access to the company property and its possible to directly call this method on our mac object (like Array.push, thats pretty cool!):
In the browser we see our new method appears under proto and "Apple" is logged to the console because we ran the new method:
Its also possible to change properties with prototypes. Here you can see how we change the ram property and also create a new property named storage with a new method we define:
The ram has changed:
With prototype inheritance we can use objective-oriented programming paradigms. More about this later on. Lets dive back into the code.
Here we create a new constructor "WorkLaptop" and use the apply keyword. It may looks confusing but its just there to call the constructor from our Computer object. In addition we create a new property "forWork". On the next line we inherit the prototype from computer to our new WorkLaptop object with Object.create (the reason: under the hood prototype is just a object):
Give yourself a few minutes and understand what exactly is happening here. We created a new constructor named WorkLaptop and called the constructor from our Computer object. We also created a new property named "forWork". Now under proto we see our new "working" method and another proto! Thats the prototype from Computer!
Now we can call "working", "changeRam" and "getCompany" on our WorkLaptop object!
Traversy Media: youtube.com/watch?v=vDJpGenyHaA&
The Net Ninja: youtube.com/watch?v=Fsp42zUNJYU&
Feel free to drop comments if you have questions or find a mistake. I love to develop myself each day and whats better for improving than mistakes? :) I wish you a nice day and stay safe.