JavaScript

Prototypal Inheritance using __proto__ in JavaScript

JavaScript does not utilize the classical inheritance, but it utilizes the prototypal inheritance. Prototypal inheritance means methods and objects can be sharable, copied, and extended. It is a very efficient strategy that reduces the time and effort of developers by sharing properties. For this purpose, the user can easily access the object properties of another object through prototypal inheritance.

How Does Prototypal Inheritance Work in JavaScript?

It is the type of inheritance that refers to an object’s ability to access the properties and methods of other objects. In JavaScript, each object has an internal property that can be accessed using the __proto__ property of prototypal inheritance.

The syntax of using the property __proto__ of Prototypal Inheritance in JavaScript is as follows.

Syntax

newObject.__proto__ = existingObject

In this syntax, the __proto__ property is utilized to share the properties of existingObject with the newObject.

Example

An example is demonstrated using the __proto__ property in JavaScript.

Code

// An example of Prototypal Inheritance using __proto__
let Car = {
name: "Honda",   // A property is a "name" that assign a value "Honda"
};

let Color= {
color: "Red",   // A property is a "color" that assign a value "Red"
};

Car.__proto__ = Color;
console.log("It  is a " + Car.color + " " + Car.name);

In the above code:

  • First, an object is defined as Car. A property name is used in this object, and its name is set to “Honda
  • Another object named Color is created in which the value “Red” is assigned to the color property.
  • Finally, the properties of the Color object are shared with the Car object using the __proto__ keyword.

In JavaScript code, the property of __proto__ is used under prototypal inheritance.

Output

The output of the above executable code is here.

The execution of JavaScript code is performed in the web browser. The output represents that the properties are shared between the objects of Car and Color using the __proto__ keyword.

Conclusion

In JavaScript, the “__proto__” keyword is used to set or get the prototype of an object. The prototypal inheritance is the phenomenon of adding the methods and properties to an object. In this method, properties are shared from one object to another object with a type of inheritance. Here, you have learned to apply the “__proto__” keyword to carry out Prototypal Inheritance. The objective of employing this property is to reduce the time and effort of developers using shared properties from another object.

About the author

Syed Minhal Abbas

I hold a master's degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.