Instance Methods: Defined on the Prototype
What you'll learn: How methods you define in a class body are automatically shared via the prototype chain.
The Automatic Prototype Connection
When you define methods inside a class body (outside the constructor), JavaScript doesn't create a separate copy of that method for each instance. Instead, it adds those methods to the class's prototype property. All instances then share that single method through their __proto__ link.
This is exactly what you'd do manually with constructor functions—adding methods to Constructor.prototype—but the class syntax handles it automatically.
How It Works
class Car {
constructor(brand) {
this.brand = brand; // instance property
}
honk() { // instance method → added to Car.prototype
console.log(`${this.brand} goes beep!`);
}
}
const car1 = new Car('Toyota');
const car2 = new Car('Honda');
car1.honk(); // "Toyota goes beep!"
// The method lives on the prototype, not the instance
console.log(car1.hasOwnProperty('honk')); // false
console.log(Object.getPrototypeOf(car1).hasOwnProperty('honk')); // true
// Both instances share the same method
console.log(car1.honk === car2.honk); // true
Why This Matters
Memory efficiency: If you created 1000 car instances, you'd have 1000 separate brand properties (each unique) but only one honk method shared by all. This saves memory and keeps your objects lightweight.
The class syntax makes this prototype-based sharing invisible and automatic—you just define methods, and JavaScript puts them in the right place.
Key Takeaway: Methods defined in a class body are automatically added to the class's prototype, allowing all instances to share the same function through the prototype chain.