Course contentsShow
← JavaScript
Lesson 716 of 2,72317. Prototypes and InheritanceFree lesson

Constructor Functions and Their prototype Property

Constructor functions define shared methods on their prototype property.

Constructor Functions and Their prototype Property

You'll learn: How constructor functions use their prototype property to define methods shared by all instances.

What This Means

When you create a constructor function in JavaScript, it automatically gets a special prototype property. This property is an object where you can attach methods and properties that should be shared across all instances created by that constructor.

Instead of defining methods inside the constructor (which would create a new copy for each instance), you define them once on Constructor.prototype. Every object created with new Constructor() will have access to these shared methods through the prototype chain.

Why It Matters

This is about efficiency and organization. If you put methods directly in the constructor body, each object gets its own copy. With the prototype property, all instances share the same method definitions, saving memory.

How It Works

function Dog(name) {
  this.name = name; // unique to each instance
}

// Define shared methods on the prototype property
Dog.prototype.bark = function() {
  return `${this.name} says woof!`;
};

const buddy = new Dog('Buddy');
const max = new Dog('Max');

console.log(buddy.bark()); // "Buddy says woof!"
console.log(max.bark());   // "Max says woof!"

// Both use the SAME bark function
console.log(buddy.bark === max.bark); // true

When you call buddy.bark(), JavaScript looks at buddy, doesn't find bark there, then checks buddy's [[Prototype]] (which points to Dog.prototype), and finds it there.

Key Takeaway: Constructor functions have a prototype property where you define shared methods—this creates one method definition that all instances can access through the prototype chain, making your code memory-efficient.