Understand Prototypal Inheritance in a simple way! π€©
Code Craft-Fun with Javascript
Posted on May 16, 2023
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}.`);
}
};
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 = "";
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.
Now, let's update the name
and grade
property of nick
object.
nick.name = "Nick";
nick.grade = "90%";
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.
We can also add a study()
method to the Student
object.
Student.study = function() {
console.log(`I am studying for my ${this.grade} grade.`);
};
Now, we can call the study()
method on the nick
object.
nick.study(); //Output: I am studying for my 90% grade.
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.
Posted on May 16, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.