Logo


Prototypal Inheritence


In programming,sometimes we want to extend something.
For instance:
we have one object which is named as a someuser with some properties and methods and on the other hand we have anpther object with its own attributes and properties. we`d like to reuse what we have in someuser object not copy its methods. Prototypal inheritance is a language feature that helps in that.
In JavaScript, objects have a special hidden property [[Prototype]] (as named in the specification), that is either null or references another object. That object is called “a prototype”:


1let animal={
2    eats:true  
3}
4let fruit={
5    Apple:"i am Apple"
6}
7fruit.__proto__=animal
8console.log("Welcome !",fruit.eats);
9

If we look for a property in rabbit , and it’s missing, JavaScript automatically takes it from nimal .
For instance:


1
2  let nimal = {
3    eats: true,
4    walk() {
5    alert("Animal walk");
6    }
7    };
8    let rabbit = {
9    jumps: true,
10    __proto__: nimal
11    };
12  

The prototype chain can be longer:




Imagine, we got a stringified meetup object from the server. It looks like this:
And now we need to deserialize it, to turn back into JavaScript object. Let’s do it by calling JSON.parse Let’s pass to JSON.parse the reviving function as the second argument, that returns all values “as is”, but date will become a Date :


1
2  let nimal = {
3    eats: true,
4    walk() {
5    alert("Animal walk");
6    }
7    };
8    let rabbit = {
9    jumps: true,
10    __proto__: nimal
11    };
12    let dog = {
13        jumps: true,
14        __proto__: mammal
15        }; 
16console.log("animal is",dog.eats) // Animal walk
17  

1let memal1 = {
2    eats: true,
3    walk() {
4    alert("Animal walk");
5    }
6    };
7    let memal2 = {
8    jumps: true,
9    __proto__: memal1
10    };
11    let memal3 = {
12    earLength: 10,
13    __proto__:memal2
14    };
15    console.log("hi",memal3.eats)
16  


About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share