Prototypal Chaining

This lesson teaches the concept of prototype chaining in detail by using an example.

Look at the following code snippet, which uses the [[Prototype]] property of objects:

Press + to interact
//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
//creating an object instance using Shape and Rectangle
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)

Let’s delve into the details of the code above.

When the prototype property of Rectangle is set to Shape, it is able to access all the properties present in Shape. So, upon accessing, if a property is not found in the object, such as if the name property is not found in Rectangle, JavaScript will automatically take it from the prototype of the object, Shape. This is known as prototypal inheritance.

Press + to interact
//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
console.log(Rectangle.__proto__)
console.log(Shape.__proto__)

As seen from the code above, since the prototype of ...