🔧 Object Prototypes

In JavaScript, prototypes are the mechanism by which objects inherit features from one another.

Every JavaScript object has a prototype—another object it inherits properties and methods from. This is known as prototypal inheritance.

Think of a prototype as a “blueprint” or a “fallback” object that JavaScript looks to when a property is not found on the original object.


🧠 How Prototypes Work

Let’s look at a simple example:

javascriptCopyEditconst person = {
  greet: function() {
    return "Hello!";
  }
};

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

console.log(student.name);    // Alice (from student)
console.log(student.greet()); // Hello! (inherited from person)
  • student doesn’t have its own greet method.
  • JavaScript looks up the prototype chain to find greet in person.

🔄 The Prototype Chain

JavaScript objects form a chain. When you try to access a property:

  1. JavaScript looks for the property on the object.
  2. If it’s not found, it looks at the object’s prototype.
  3. This continues up the chain until null is reached.
javascriptCopyEditconsole.log(student.toString()); // Found on Object.prototype

All objects eventually inherit from Object.prototype.


🧱 Using Constructor Functions and Prototypes

Instead of copying methods into each object, JavaScript uses prototypes to share methods efficiently.

Example:

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

Person.prototype.greet = function() {
  return `Hi, I’m ${this.name}`;
};

const p1 = new Person("Bob");
console.log(p1.greet()); // Hi, I’m Bob
  • greet is added to Person.prototype.
  • All Person instances share the same greet function.

This saves memory and keeps code clean.


🛠️ Modifying Prototypes

You can add methods to existing prototypes:

javascriptCopyEditArray.prototype.sayHello = function() {
  return "Hello from Array!";
};

const nums = [1, 2, 3];
console.log(nums.sayHello()); // Hello from Array!

⚠️ Note: Avoid modifying built-in prototypes like Array.prototype in production. It can cause bugs in other code.


🆕 ES6 Class Syntax (Under the Hood Uses Prototypes)

The modern class syntax in JavaScript is syntactic sugar over prototypes.

javascriptCopyEditclass Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    return `Hello, I’m ${this.name}`;
  }
}

const p = new Person("Alice");
console.log(p.greet()); // Hello, I’m Alice

This is equivalent to using constructor functions and Person.prototype.


✅ Key Takeaways

  • Every object in JavaScript has a prototype.
  • Prototypes allow objects to inherit properties and methods.
  • You can use Object.create(), constructor functions, or class to work with prototypes.
  • Prototypes are efficient: shared behavior doesn’t need to be copied to every object.
  • Modern JavaScript often hides prototypes behind class syntax, but understanding them is essential.