JavaScript Prototypes & Inheritance


What is a Prototype in JavaScript?

In JavaScript, every object has a hidden property called [[Prototype]] (accessible via __proto__), which points to another object. This forms a prototype chain.

Think of it as a blueprint or fallback for properties/methods not found on the object itself.



Prototype Chain

const person = {
  greet: function () {
    console.log("Hello!");
  }
};

const student = Object.create(person);
student.name = "John";

student.greet(); // Output: Hello!

Here, student doesn't have greet, but it inherits from person via the prototype chain.



Constructor Functions and Prototypes

function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function () {
  console.log(`${this.name} makes a noise.`);
};

const dog = new Animal("Dog");
dog.speak(); // Output: Dog makes a noise.
  • speak is not directly on dog, but on Animal.prototype.


Prototypal Inheritance

You can set one constructor to inherit from another:

function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function () {
  console.log(`${this.name} makes a noise.`);
};

function Dog(name, breed) {
  Animal.call(this, name); // Inherit properties
  this.breed = breed;
}

Dog.prototype = Object.create(Animal.prototype); // Inherit methods
Dog.prototype.constructor = Dog;

Dog.prototype.bark = function () {
  console.log(`${this.name} barks!`);
};

const dog = new Dog("Rex", "Labrador");
dog.speak(); // Rex makes a noise.
dog.bark();  // Rex barks!


ES6 Class Syntax (Simplified Inheritance)

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  bark() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog("Charlie");
dog.speak(); // Charlie makes a sound.
dog.bark();  // Charlie barks.
  • extends handles the prototype linkage.
  • super() calls the parent class constructor.


Visual Representation

Imagine this chain:

dog --> Dog.prototype --> Animal.prototype --> Object.prototype --> null

Every object inherits from Object.prototype by default unless manually changed.



Summary Table

Concept Description
prototype Property on functions for shared methods
__proto__ Internal reference to an object's prototype
Inheritance Child object inherits from parent via prototype
Constructor Function used to create instances
class / extends Modern syntax for creating and inheriting classes