Hey everybody today i am going to tell you something about javascript's prototypes and inheritance.Many beginners face challenge while learning it so i am here to make things super simple and crystal clear for you...
So first of all what are prototypes? So lets see a screenshot below
so as you can see we have created an object in which we have a property name and inside it we have an object prototype in which we have many properties and all those properties are automatically inherited by the object 'a'.Not only object 'a' everything we make in the javascript will inherit the properties of Prototype because everything in javascript are objects.
so it is like a chain in which first object 'a' is coming and inheriting the properties of Prototype and then a null will come that means this chain has ended and there are no further properties. This chain is also called Prototype chain.
We can create this chain by us like in the code below...
let obj1 = {
name:"abc",
age:5,
speak:function(){
console.log("hello reader!");
}
}
//first way to create and inherit the object
let obj2 = Object.create(obj1); //cons of this way is that we will not be alble to give more properties to obj2
So with the help of Object.create() we can create an object that will inherit the properties of the object given in the arguments.Also we can give null in the arguments to make the prototype null that means chain will end there.
Here our chain will look like
obj1 <--- obj2<---Object.prototype<--null
Now lets do it will other ways in the following code...
let obj1 = {
name:"abc",
age:5,
speak:function(){
console.log("hello reader!");
}
}
let obj2 = {
//here we can add more properties unlike Object.create()
__proto__:obj1 //obj2 will inherit the properties of obj1
}
Nowadays it is recommended not to use __ proto __ .Instead we can use Object.setPrototypeOf().Lets learn it using code...
const a = {
num:3,
add:function(){
console.log(this.num +1)
}
}
const b = {
num:4 //property shadowing
}
Object.setPrototypeOf(b,a); // (b inherits a )
So we have seen many ways to do inheritance...
and ya if you are wondering what is 'Property Shadowing'.I will write my next blog on it while keeping it short and simple...
Prototype chaining resolution/Property lookup
So now we know what are prototypes, what is prototype chain and different methods to do inheritance...
now let us talk about property lookup.It is basically the searching of the property requested by the object inside the Prototype chain...If we get that property it will be executed and if it is not found and control reaches to null then 'undefined' would be printed by the compiler.
Thank you everyone for reading my blog ,I hope you have liked it and sorry if it seems unprofessional because its my first time writing a blog!!!
~by Jesmeek Singh Bhugra