...

/

Prototypal Chaining

Prototypal Chaining

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

In the previous lesson, the [[Prototype]] property of objects was discussed.

We discussed the following code:

Press + to interact
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
//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 the name property is not found in Rectangle, JavaScript will automatically take it from the prototype of that object, Shape. This is known as prototypal inheritance. ...

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy