Classes vs Prototypes

JavaScript objects inherit features from prototypes. Understanding how classes relate to prototypes is key to mastering object-oriented JavaScript.

Illustration of classes_vs_prototypes
Illustration of classes_vs_prototypes

💡 Prototype Basics

Every JavaScript object has a hidden link to another object called its prototype. This link forms a chain used for inheritance.

Prototypes: The Core of Inheritance

Before ES6, prototypes were the main way to create reusable methods for objects.

📌 Deep Dive: Prototype Example

JAVASCRIPT
function Person(name) {
  this.name = name;
}

Person.prototype.greet = function() {
  return `Hello, my name is ${this.name}`;
};

const alice = new Person('Alice');
console.log(alice.greet()); // Hello, my name is Alice
Output
Hello, my name is Alice

Classes: Syntactic Sugar Over Prototypes

ES6 introduced class syntax, which simplifies creating constructor functions and prototype methods.

📌 Deep Dive: Class Example

JAVASCRIPT
class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return `Hello, my name is ${this.name}`;
  }
}

const bob = new Person('Bob');
console.log(bob.greet()); // Hello, my name is Bob
Output
Hello, my name is Bob
Comparison: Prototypes vs Classes
AspectPrototypesClasses
SyntaxFunction constructor + .prototypeclass keyword with methods inside
ReadabilityLess intuitive for beginnersClear, OOP-friendly syntax
InheritanceManual prototype chainingextends keyword for subclassing
Under the hoodBoth use prototypes internallyClasses are syntactic sugar over prototypes
HoistingFunction constructors are hoistedClass declarations are not hoisted

⚠️ Important Note

Despite the clear syntax, class in JavaScript is not a new object model but a cleaner way to work with prototypes. Understanding prototypes remains essential.

Prototype Chain Check

You can verify that class methods are on the prototype:

📌 Deep Dive: Prototype Chain with Classes

JAVASCRIPT
class Animal {
  speak() {
    return '...';
  }
}

const dog = new Animal();

console.log(dog.speak()); // '...'
console.log(Object.getPrototypeOf(dog) === Animal.prototype); // true
Output
...
true

💡 Summary

  • Prototypes are the foundation of inheritance in JavaScript.
  • Classes make working with prototypes easier and more readable.
  • Both achieve the same underlying mechanism: methods are stored on the prototype object.
  • Learning prototypes helps you understand the behavior of classes deeply.