Dhananjay Patel Logo
  1. Home
  2. / Blog
  3. / Advance Js Concept
  4. / Lessons
  5. / 4

Prototypal Inheritance

In JavaScript, objects can inherit properties and methods from other objects. This is done through the prototype chain, allowing one object to use the properties of another.

Javascript info: https://javascript.info/prototype-inheritance

Example

function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person1 = new Person("Alice", 25);
person1.greet(); // Output: Hello, my name is Alice

Explanation: Here, the greet method is added to the Person prototype, allowing all instances of Person to share this method without redefining it.

Application: Prototypal inheritance is used to implement inheritance, allowing for more efficient memory usage by sharing methods across instances.