Search⌘ K
AI Features

Prototype Property

Explore how to use the __proto__ property to access and modify an object's prototype in JavaScript. Understand prototype inheritance by examining how one object inherits properties from another, enhancing your grasp of JavaScript’s prototypal inheritance system and object relationships.

We'll cover the following...

__proto__ Property

In JavaScript, objects contain a property [[Prototype]] that is hidden. This property either points to another object or is null.

The [[Prototype]] property of objects, i.e., anObject.[[Prototype]] defines the prototype of anObject. It is defined through the __proto__ property which is used as a setter/getter for the [[Prototype]] property; i.e., __proto__ is used in order to access/set the [[Prototype]] property of an object.

Syntax

Let’s take a look at the syntax for accessing and setting the [[Prototype]] property of an object.

Javascript (babel-node)
//using __proto__ to access and set the [[Prototype]] of "anObject"
anObject.__proto__ = someotherObject

Example

Let’s take a look at an example to make this concept more clear.

Javascript (babel-node)
//Shape object
var Shape={
name: 'Rectangle',
sides: 4
}
//Rectangle object
var Rectangle = {
length: 3,
width: 5
}
//setting [[Prototype]] of Rectangle equal to Shape
Rectangle.__proto__ = Shape
//displaying Rectangle object's properties
console.log("Name of shape is:",Rectangle.name)
console.log("Number of sides are",Rectangle.sides)
console.log("Length is:",Rectangle.length)
console.log("Width is:",Rectangle.width)

Explanation

As seen in the code above:

  • Two objects Shape and Rectangle are created.

  • Shape contains the properties:

    • name
    • sides
  • At the start, Rectangle contains the properties:

    • length
    • width
  • In line 14, the __proto__ property sets Rectangle's [[Prototype]] property equal to Shape.

Line 14 can translate to:

Shape is the prototype of Rectangle

or

Rectangle inherits prototypically from Shape