Understanding the JavaScript Prototype Chain

JavaScript Logo

Prototypes are the mechanism by which JavaScript objects inherit features from one another. Every JavaScript object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on, until an object is reached with `null` as its prototype. This is the prototype chain.

How It Works

When you try to access a property of an object, JavaScript first checks if the property exists on the object itself. If not, it looks at the object's prototype. If it's still not found, it checks the prototype's prototype, and so on, up the chain.

Example

// Constructor function
function Dog(name) {
  this.name = name;
}

// Add a method to the Dog's prototype
Dog.prototype.bark = function() {
  console.log('Woof!');
};

const myDog = new Dog('Rex');

myDog.bark(); // 'bark' is not on myDog, but on its prototype.

// The chain:
// myDog ---> Dog.prototype ---> Object.prototype ---> null

console.log(Object.getPrototypeOf(myDog) === Dog.prototype); // true
console.log(myDog.toString()); // 'toString' is found on Object.prototype

In this example, `myDog` doesn't have its own `bark` method. When `myDog.bark()` is called, JavaScript looks up the prototype chain, finds `bark` on `Dog.prototype`, and executes it.

Understanding the prototype chain is key to understanding inheritance in JavaScript, especially in pre-ES6 class syntax.

Comments