Prototypes are the mechanism by which JavaScript objects inherit features from one another.
In JavaScript, everything is an object, including functions, arrays, and strings, which are specialized types of objects. JavaScript follows a prototype-based system, where objects inherit properties and methods from other objects through prototypes. This prototype mechanism plays a key role in how JavaScript handles inheritance and object relationships.
So in JavaScript, every object has a prototype, which is an object that serves as a template for the object's properties and methods. The prototype is a container for methods and properties. When methods or properties are added to the prototype of a function, array, or string, they become shared by all instances of that particular object type. Prototype in general can be understood as a mold, and all its instances can be considered as the car made from it.
We can demonstrate this by creating an array:
- const arr = [1, 2, 3];
- arr
- (3) [1, 2, 3];
- 0: 1
- 1: 2
- 2: 3
- [[ prototype ]]
Now we did not assign the prototype to the array, Javascript did. And if you expand the prototype, you will see a list of all of the prototype methods associated with this object. Methods such as push() and pop(). And because these methods are defined within the prototype, they will be available to ALL array objects. This is the basis for how prototypes work.
We can create our own methods in an object, such as:
- arr.lol = function() {
- console.log('lololol');
- }
However, Houston we have a problem. If we look at the array breakdown in the console,:
- (3) [1, 2, 3];
- 0: 1
- 1: 2
- 2: 3
- lol: f ()
- [[ prototype ]]
What this means is that this lol() method will only be available for use within the scope of this individual array object. It will not be available for use within any other array object.
To make this new function available to All array objects, we would define it like so:
- Array.prototype.lol = function() {
- console.log('lololol');
- }
- 1st) we are adding to the "Array" object, not our individual array, so we assign the new function to Array.prototype.
- 2nd) You must capitalize the first letter of the object name Array.
- (3) [1, 2, 3];
- 0: 1
- 1: 2
- 2: 3
- [[ prototype ]]
- lol: f ()
- ...
- ...
- ...
*note assigning our new method does have one limitation. It will only be accessible until the page is refreshed. Once the page is refreshed, the array object is reset, and the new method goes away.
Another thing to note is that you can change the functionality of existing methods. For example, if we use the pop() method, we remember that pop() removes the last item in an array object. We can change this default functionality, like so:
- Array.prototype.pop = function() {
- console.log('I\'m Sorry, but I wish to keep this item!!');
- }
- arr.pop()