Prototypes | Dataplexa

Prototypes

Before ES6 classes existed, JavaScript used prototypes to share properties and methods between objects.

Even today, classes internally work on top of prototypes. Understanding prototypes helps you truly understand JavaScript.


What Is a Prototype?

Every JavaScript object has an internal link to another object called its prototype.

When you access a property or method on an object, JavaScript looks for it:

  • First on the object itself
  • If not found, on its prototype
  • Then further up the prototype chain

A Simple Example


let user = {
  name: "Alex"
};

console.log(user.toString());
  

Even though toString() is not defined on user, it still works because it exists on the prototype.


The Prototype Chain

JavaScript forms a chain of objects behind the scenes.

If a property is not found, JavaScript keeps searching up the chain until it reaches null.

This mechanism is called the prototype chain.


Constructor Functions and Prototypes

Before classes, constructor functions were used to create multiple similar objects.


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

User.prototype.greet = function () {
  return "Hello " + this.name;
};

let user1 = new User("Sara");
  

The greet() method is shared across all instances.


Why Prototypes Matter

  • Save memory by sharing methods
  • Enable inheritance-like behavior
  • Power JavaScript’s object system

Without prototypes, JavaScript objects would be inefficient.


Classes and Prototypes

When you write a class:


class User {
  greet() {
    return "Hello";
  }
}
  

JavaScript actually places greet() on the prototype behind the scenes.

Classes just provide cleaner syntax.


Real-World Analogy

Think of a prototype like a shared instruction manual.

  • Each object follows the same instructions
  • No need to copy instructions for every object

This makes systems efficient and consistent.


Common Beginner Confusions

  • Thinking prototypes are copied
  • Confusing prototypes with classes
  • Modifying prototypes without understanding impact

Prototypes are linked, not duplicated.


Thumb Rules

  • Every object has a prototype
  • Methods are usually stored on prototypes
  • Classes still rely on prototypes
  • Prototype chain explains method lookup

What Comes Next?

Now that you understand prototypes, the next step is seeing how objects can inherit behavior from other objects.

In the next lesson, we will explore inheritance.