CodePark/ questions / Prototypes & classes
START PRACTICINGPRACTICE
Frontend question · JavaScript › Prototypes & classes

Explain prototypal inheritance and the prototype chain.

Each object has a hidden link to another object, called its prototype. When a property is missing on the object, JavaScript looks for it on the prototype, then on the prototype's prototype, and so on. This series of links is the prototype chain.

The hidden link is called [[Prototype]]. It points to another object or to null. The lookup stops when it finds the property, or when it reaches null. Then it returns undefined.

This is how objects share methods. For example, [1, 2].map is not stored on the array itself. It lives on Array.prototype, and the prototype of Array.prototype is Object.prototype.

Writing is different from reading. Writing a property always creates or updates it on the object itself. This new own property shadows (hides) the prototype's version.

You can set a prototype in three ways:

  • Object.create(proto)
  • a constructor function called with new, which links the instance to Constructor.prototype
  • class syntax

To read the prototype, use Object.getPrototypeOf. __proto__ also works, but it is an old (legacy) accessor.

  • Each object links to a prototype through the hidden [[Prototype]] slot.
  • Reading a property walks up the chain until it finds the property or reaches null.
  • Writing a property creates an own property that hides the inherited one.
  • new F() links the new instance to F.prototype.
  • Use Object.create and Object.getPrototypeOf. __proto__ is legacy.