Web Analytics

Prototypes & Inheritance

Advanced ~25 min read

What is a Prototype?

JavaScript is a prototype-based language. All JavaScript objects inherit properties and methods from a prototype.

  • Date objects inherit from Date.prototype
  • Array objects inherit from Array.prototype
  • Person objects inherit from Person.prototype

The Prototype Chain

When you try to access a property of an object:

  1. JavaScript first checks if the object itself has the property.
  2. If not, it looks at the object's prototype.
  3. If not there, it looks at the prototype's prototype.
  4. This continues until it reaches Object.prototype (the top of the chain).

HTML
CSS
JS

Adding Properties to Prototypes

You can add new properties or methods to all existing objects of a given type by adding them to the prototype.

HTML
CSS
JS
Warning: Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects (like Array.prototype) as this can cause conflicts with other libraries.

Prototypal Inheritance

Before ES6 Classes, prototypes were the primary way to implement inheritance in JavaScript.

HTML
CSS
JS

Summary

  • Every JavaScript object has a prototype.
  • Objects inherit properties and methods from their prototype.
  • The prototype chain allows for property lookups up the hierarchy.
  • You can extend constructors by adding to their .prototype.

Quick Quiz

What is the top of the prototype chain?

A
Array.prototype
B
Function.prototype
C
Object.prototype
D
Window.prototype