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.
Example
Let’s take a look at an example to make this concept more clear.
Explanation
As seen in the code above:
-
Two objects
ShapeandRectangleare created. -
Shapecontains the properties:namesides
-
At the start,
Rectanglecontains the properties:lengthwidth
-
In line 14, the
__proto__property setsRectangle's[[Prototype]]property equal toShape.
Line 14 can translate to:
Shape is the prototype of Rectangle
or
Rectangle inherits prototypically from Shape