Prototypal Inheritance in javascript

   


Before getting into prototypal inheritance first, we will see what is  __proto__ object?


Eg:-

Have you seen when you create an (object/array/string/function) will have some function/property in it?





On the above image, we used to create an object, where we can able to access some functions like hasOwnProperty which is not created by myself, How?


let we start from AST for (let a = {}).




Here `a` is the variable declared with ObjectExpression by which it creates new instance of constructor function called Object, that's how the properties of Object get inherited into variable 'a'.




Those inherited properties can be accessed by calling  a.__proto__.




In basic __proto__ is an object which has inherited properties from its parent object.


Prototypal Inheritance:

When we search for a property that we didn’t define in a variable it will travel in the prototype chain to find property from its prototype chain this is known as prototypal inheritance.


Eg:-

let a = {};

when we didn't define any property in it, but we can access the toString function from a.

where toString is the function which is the property of the Object.




What is the prototype and what is the difference between prototype and __proto__?


The prototype is the object which can be found only in the constructor function, but the properties in the prototype can be accessed by the instance of the constructor function.


__proto__ is the object in every variable which has the inherited properties from its parent object.

prototype is the object which contains all properties which will be inherited to its instance.



No comments: