Understand Prototypal Inheritance in a simple way! 🀩

codecraftjs

Code Craft-Fun with Javascript

Posted on May 16, 2023

Understand Prototypal Inheritance in a simple way! 🀩

Prototypal Inheritance in Javascript

important Interview question for a Javascript developer

Prototypal inheritance is a fundamental concept in JavaScript that allows objects to inherit properties and methods from a parent object. In this blog post, we will explore how prototypal inheritance works in JavaScript with some examples. Kindly visit my previous blog to understand more about Prototypes and Prototype chaining before reading further.

At the heart of prototypal inheritance is the concept of a prototype, which is an object that serves as a blueprint for creating other objects. Every object in JavaScript has a prototype, which can be accessed using the __proto__ property.

Let's start with a simple example. Suppose we have a Person object that has a name property and a greet() method.

let Student = {
  name: "",
  greet: function() {
    console.log(`Hello, my name is ${this.name}.`);
  }
};

Enter fullscreen mode Exit fullscreen mode

Now, we want to create a nick object that inherits from the Student object and has an additional grade property. We can do this by creating a new object and setting its prototype to be the Student object.

let nick = Object.create(Student);
nick.grade = "";

Enter fullscreen mode Exit fullscreen mode

As you can see in the below image, the nick object's __proto__ property contains the properties of Student object. This means that nick object has inherited the properties from its parent Student object.

example

Now, let's update the name and grade property of nick object.

nick.name = "Nick";
nick.grade = "90%";

Enter fullscreen mode Exit fullscreen mode

We can call the greet() method on the nick object, which will use the name property inherited from the Student object.

nick.greet(); // Output: Hello, my name is Nick.

Enter fullscreen mode Exit fullscreen mode

We can also add a study() method to the Student object.

Student.study = function() {
  console.log(`I am studying for my ${this.grade} grade.`);
};

Enter fullscreen mode Exit fullscreen mode

Now, we can call the study() method on the nick object.

nick.study(); //Output: I am studying for my 90% grade.

Enter fullscreen mode Exit fullscreen mode

In summary, prototypal inheritance in Javascript is a powerful feature that allows objects to inherit properties and methods from a parent object. By setting an object's prototype to another object, we can create a hierarchy of objects that share common properties and methods.

πŸ’– πŸ’ͺ πŸ™… 🚩
codecraftjs
Code Craft-Fun with Javascript

Posted on May 16, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related