Skip to content

Prototypes

JavaScript uses prototype-based inheritance β€” every object has an internal link ([[Prototype]], accessible via Object.getPrototypeOf() or the older __proto__) to another object it can borrow properties and methods from. When you access a property that doesn’t exist on an object itself, JavaScript walks up this β€œprototype chain” until it finds it (or reaches null). class syntax is built on top of this same mechanism.

const animal = {
eat() { return `${this.name} is eating`; },
};
const dog = Object.create(animal); // dog's prototype is `animal`
dog.name = "Fido";
console.log(dog.eat()); // "Fido is eating" -- found via the prototype chain
// class syntax is prototype-based under the hood
class Animal {
constructor(name) { this.name = name; }
eat() { return `${this.name} is eating`; }
}
class Dog extends Animal {
bark() { return `${this.name} says Woof!`; }
}
const fido = new Dog("Fido");
console.log(fido.eat()); // inherited from Animal's prototype
console.log(fido instanceof Animal); // true

Adding methods directly inside a constructor function instead of on its .prototype β€” this creates a brand new copy of the function for every instance, wasting memory instead of sharing one implementation.

// Wasteful -- every instance gets its own copy of `eat`
function Animal(name) {
this.name = name;
this.eat = function () { return `${this.name} is eating`; };
}
// Efficient -- one shared function on the prototype, used by all instances
function Animal(name) {
this.name = name;
}
Animal.prototype.eat = function () {
return `${this.name} is eating`;
};
  1. What happens when you access a property that doesn’t exist directly on an object?

    AnswerJavaScript walks up the prototype chain, checking each linked object in turn, until it finds the property or reaches the end of the chain (null), returning undefined if it's never found.
  2. Is JavaScript’s class syntax a different inheritance model from prototypes?

    AnswerNo β€” class is syntax sugar over the same prototype-based system; methods defined in a class body end up on the class's .prototype.
  3. Why is defining methods on .prototype more memory-efficient than defining them in the constructor?

    AnswerA prototype method is created once and shared by every instance via the prototype chain; a method assigned inside the constructor is recreated as a brand-new function for each instance.