Mark As Completed Discussion

Inheriting Properties and Methods with Prototypical Inheritance

Objects are not merely isolated entities; they possess intricate relationships that shape their behavior. One such relationship is prototypal inheritance, a mechanism that allows objects to inherit properties and methods from other objects, forming a hierarchical lineage.

Imagine a grand tapestry woven with threads of interconnectedness, each thread representing an object. This tapestry is the prototype chain, where objects inherit traits from their ancestors, much like children inherit traits from their parents.

To illustrate this concept, let's consider the familiar example of a car and its relationship to the broader category of vehicles:

JAVASCRIPT
1const car = {
2  name: "BMW",
3  power: "2000 BHP",
4  color: "black"
5};
6
7console.log(car);
8console.log(car.name);
9console.log(car.power);
10console.log(car.color);

Examining the car object in the console reveals a link to the Object prototype, the foundation of all JavaScript objects. This connection grants the car access to the vast array of properties and methods inherent in the Object prototype.

Inheriting Properties and Methods with Prototypical Inheritance

Now, let's introduce a new object, vehicle, representing the generic concept of a vehicle:

JAVASCRIPT
1const vehicle = {
2  wheels: 4
3};

Here, we define a property called wheels with a value of 4, establishing a default value for the number of wheels for any vehicle.

To connect the car to this broader vehicle category, we employ the Object.setPrototypeOf() method:

JAVASCRIPT
1Object.setPrototypeOf(car, vehicle);
2
3console.log(car.wheels);

By assigning vehicle as the prototype of car, we establish a hierarchical relationship, empowering the car to inherit properties from its vehicle ancestor. Printing the wheels property of the car object now yields the value 4, demonstrating the successful inheritance of this trait.

This mechanism extends to methods as well, as methods in JavaScript are essentially properties of objects. Prototypical inheritance enables objects to inherit the functionality of their ancestors, promoting code reuse and maintainability.