Prototype and prototypal inheritance

Prototype and prototypal inheritance

In this article, we are going to cover:

  • Prototype
  • Prototype chain
  • Prototypal inheritance

start.gif

Do you ever wonder how we get access to all the build-in methods in javascript? even if we write array, object, function, even a variable almost everything in js has access to the build-in methods. so how does this possible? this is possible because of the prototypes in javascript.

Screenshot (956).png

Screenshot (957).png

Screenshot (958).png

Prototype

Prototype is just an object that attaches to almost anything we create functions, objects, arrays, ... in javascript by the js engine.

p.s. if you wanna access this prototype just add .__proto__ to any property you have created in js.

Screenshot (960).png

Prototype Chain

Screenshot (962).png

As you see the prototype of an array is Array. prototype and if you take the prototype of Array. prototype it is Object. prototype and the prototype of Object. prototype is null that is the end of a chain.

Screenshot (965).png

Here you can see that the obj prototype is Object. prototype and prototype of Object. prototype is null and this is the end of a chain.

Screenshot (966).png

Here you can see the fn prototype is Function. prototype and the prototype of Function. prototype is Object. prototype and the prototype of Object. prototype is null and this is the end of a chain.

this is how everything in javascript is ended up being an object in down the chain of prototypes

Prototypal Inheritance

const obj={
 name: "Sanket",
 state: "Maharashtra",
 getInfo: function(){
    console.log(this.name + " from "+ this.state);
 }
}

const obj2={
 name: "Sandesh"
}

// never do this just for understanding purpose
obj2.__proto__ = obj;

By setting up the prototype of obj2 as obj we can access the property of obj in obj2 like:

obj2.name // Sandesh

obj2.state // Maharashtra

obj2.getInfo() // Sandesh from Maharashtra

Just because only name property is present in obj2 this keyword points to obj2 so print the name property but the state property is in obj still able to get access to it inside obj2. this is known as a prototypal inheritance in js.

That's it for this article!

thank you.gif