Advance JavaScript (DOM, BOM, Web API) / Object Oriented Programming

.prototype

✅ What is .prototype?

  • .prototype is a property available only on functions (specifically constructor functions).

  • It stores an object.

  • That object becomes the [[Prototype]] (a.k.a. __proto__) of all instances created from that function using new.


🔹 1. .prototype Exists Only on Functions

Every function in JavaScript automatically gets this property:

function Person() {}
console.log(Person.prototype); // { constructor: f Person() }
  • Objects do NOT have .prototype

  • Only functions do


🔹 2. Instances Get __proto__ (or [[Prototype]])

When you create an object using new, the instance's __proto__ points to the function's .prototype:

function Person() {}

const p1 = new Person();

console.log(p1.__proto__ === Person.prototype); // true

.prototype belongs to the function

__proto__ belongs to the instance

These two link together to form the prototype chain.


🧩 3. Adding Methods Using .prototype

Using .prototype, you can add shared methods:

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

Person.prototype.sayHello = function() {
  console.log("Hello, " + this.name);
};

const p1 = new Person("Bhaskar");
const p2 = new Person("Das");

p1.sayHello(); // works
p2.sayHello(); // works

✔ Both objects share the same sayHello

✔ Memory efficient

Avoid this

function Person (name) {
	this.name = name;
	this.sayHello = function() {
  console.log("Hello, " + this.name);
	};
}

We Should Avoid Defining Methods Inside the Constructor.

Because every object gets its own separate copy of the method — wasting memory.


🏗 4. Constructor Property

Every .prototype object has a constructor property pointing back to the function:

Person.prototype.constructor === Person // true
console.log(Person.prototype); // { constructor: f Person() }

Useful for identifying which constructor created an object.


❓Why Prototypes Exist

1. To Enable Inheritance in JavaScript

Before class syntax existed, prototypes allowed:

  • shared behavior

  • method reuse

Without prototypes:

  • ❌ duplicated code

  • ❌ wasted memory

With prototypes:

  • ✅ one shared method

  • ✅ clean memory usage

2. To Avoid Copying Common Methods

Methods like:

  • toString()

  • hasOwnProperty()

  • isPrototypeOf()

are not copied to every object.

They live inside:

Object.prototype

So all objects can access them through inheritance instead of duplication.

Object.prototype is the root prototype of almost everything in JavaScript.