Prototypes in JS

What is Prototype?
Prototypes are the mechanism by which JavaScript objects inherit features from one another.In JavaScript, objects can inherit features from one another via prototypes. Every object has its own property called a prototype. Because the prototype itself is also another object, the prototype has its own prototype. This creates a something called prototype chain. The prototype chain ends when a prototype has null for its own prototype.
Let’s write an object in our browser:
let person={name:"john"}
It we want to access the property of the object we will use the dot operator.

When you try to access a property of an object: if the property can't be found in the object itself, the prototype is searched for the property. If the property still can't be found, then the prototype's prototype is searched, and so on until either the property is found, or the end of the chain is reached, in which case undefined is returned.

Here the toString() method doesn’t exist in the object person but exists in the prototype Object of the person.

We can access the prototype of an object, array or function using “__proto__”. It returns the prototype of the object and continues until null is reached.

Adding our own properties to prototype
We can add our own methods and properties to the prototype of an object. For example, person be an object and it’s properties doesn’t hold greet() method. The greet() method is also not present in Object.prototype. To assign it to the Object method we will write the following code:

You can also use Object.assign() method to achieve the above.
Prototypal Inheritance
Prototypes are a powerful and very flexible feature of JavaScript, making it possible to reuse code and combine objects.
In particular they support a version of inheritance. Inheritance is a feature of object-oriented programming languages that lets programmers express the idea that some objects in a system are more specialized versions of other objects.
For example, we have a general prototype object computer with ram and cpu props. We want to create an object lenovo. Since it’s a computer only thing that will differ will be the Screen type, the cpu and ram will stay same and it will be meaningless to copy paste it. So, here we will use __proto__ to inherit the properties of computer object into lenovo.
let computer={ram:16,cpu:4}
let lenovo={screen:"HD"}
Object.assign(lenovo,computer)
console.log(lenovo.ram) // 16
Old way to write it:
let computer={ram:16,cpu:4}
let lenovo={screen:"HD",__proto__:computer}
console.log(lenovo.ram)
// 16

Conclusion
This articles covers the topics of prototype chaining, prototypal inheritance and how they are useful. That’s it for this one, see you again in the next one. Happy Coding!! :)




