How does the prototypal inheritance works in JavaScript?

Need for Prototypal Inheritance in JavaScript

Prototypal inheritance is fundamental in JavaScript because it provides a mechanism for objects to inherit features from other objects. This form of inheritance is more flexible and less restrictive than classical inheritance models, making it well-suited to the dynamic and diverse nature of JavaScript environments. It simplifies the object creation process, enhances code reusability, and improves memory efficiency.

What is Prototypal Inheritance

Prototypal inheritance is a method by which objects in JavaScript can inherit properties and methods from other objects. The system is based on the concept of prototypes—each object can have a prototype object, which acts as a template object from which it inherits methods and properties.

How Does It Work

Prototype Object: Each JavaScript object has a property that points to another object, known as its prototype. The prototype object itself may also have a prototype, and so on, creating a "prototype chain."

Property Lookup: When you attempt to access a property or method of an object, JavaScript first looks at the object’s own properties. If it doesn’t find it there, it looks up the prototype chain. This search continues until the property is found or the end of the chain is reached (typically Object.prototype which is the root of the prototype chain).

Creating Objects: JavaScript provides various ways to set an object’s prototype. The simplest is using Object.create(proto), which creates a new object with proto as its prototype. Constructor functions and the new keyword also use prototypal inheritance by assigning the prototype of the new object to the object referenced by the constructor function's prototype property.

Example of Inheritance:


let animal = {
isAlive: true,
eat: function() { console.log("Eating"); }

};

let rabbit = Object.create(animal);

rabbit.hop = function() { console.log("Hopping"); };

rabbit.hop(); // Output: "Hopping"

rabbit.eat(); // Output: "Eating" (inherited from the animal prototype)