Prototype Property
This lesson explains the prototype property of objects and what __proto__ is used for by using an example.
We'll cover the following
__proto__
Property
As discussed, in JavaScript the 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., in order to access/set the [[Prototype]]
property of an object __proto__
is used.
Syntax
Let’s take a look at the syntax for accessing and setting the [[Prototype]]
property of an object.
//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.
//Shape objectvar Shape={name: 'Rectangle',sides: 4}//Rectangle objectvar Rectangle = {length: 3,width: 5}//setting [[Prototype]] of Rectangle equal to ShapeRectangle.__proto__ = Shape//displaying Rectangle object's propertiesconsole.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
andRectangle
are created. -
Shape
contains the properties:name
sides
-
At the start,
Rectangle
contains the properties:length
width
-
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
What do both of the above lines mean? Why does the code above display the name
and sides
value when accessed from Rectangle
? Let’s discuss the answers to these questions in the next lesson.