Understanding Prototype in JavaScript

📌 What is a Prototype?

In JavaScript, every object has an internal property called [[Prototype]] (commonly accessed via __proto__ or Object.getPrototypeOf()). This is part of JavaScript's prototypal inheritance system. 💡

Note

Prototypes allow objects to inherit properties and methods from other objects, enabling efficient memory use and shared behavior.

🧪 Creating a Prototype Chain

Using Function Constructor and Prototype

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

// Add method to prototype
Person.prototype.sayHello = function () {
  console.log("Hello, I am " + this.name);
};

const user = new Person("Alice");
user.sayHello(); // Hello, I am Alice

The sayHello method is not directly on the user object — it's in the Person.prototype, which user inherits from. 🧠

🔍 How Inheritance Works

When you access a property or method on an object:

  • JavaScript checks the object itself.
  • If not found, it looks up the prototype chain.
  • This continues until the property is found or null is reached.

Note

The top of every prototype chain is Object.prototype, which contains common methods like toString(), hasOwnProperty(), etc.

🔁 Example: Inheritance Chain

Prototypal Inheritance Chain

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

Animal.prototype.speak = function () {
  console.log(this.name + " makes a sound.");
};

function Dog(name) {
  Animal.call(this, name);
}

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

Dog.prototype.bark = function () {
  console.log(this.name + " barks.");
};

const rex = new Dog("Rex");
rex.speak(); // Rex makes a sound.
rex.bark();  // Rex barks.

Here, Dog inherits from Animal using Object.create(). This sets up a prototype chain from rex → Dog.prototype → Animal.prototype. 🔗

⚠️ Beware of Overwriting Prototypes

Note

Overwriting an entire prototype object (e.g., Constructor.prototype = {...}) removes the original constructor reference. Always reset it if needed.

Fixing Constructor Reference

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // 🔧 Important

🧪 Checking Prototypes

Prototype Inspection

console.log(rex.__proto__ === Dog.prototype); // true
console.log(Dog.prototype.__proto__ === Animal.prototype); // true
console.log(Object.getPrototypeOf(rex)); // Dog.prototype

✨ Summary

  • Every object in JavaScript has a prototype
  • Prototypes enable inheritance and shared methods
  • Use Constructor.prototype to define shared methods
  • Object.create() sets up inheritance between prototypes

📚 Learn More

>>“Objects inherit from objects — not classes. This is the heart of JavaScript's prototype chain.” 🔗