Prototypes
Prototypes
Section titled βPrototypesβWhat it means
Section titled βWhat it meansβ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.
Examples
Section titled βExamplesβ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 hoodclass 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 prototypeconsole.log(fido instanceof Animal); // trueCommon mistake
Section titled βCommon mistakeβ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 instancesfunction Animal(name) { this.name = name;}Animal.prototype.eat = function () { return `${this.name} is eating`;};Quick practice
Section titled βQuick practiceβ-
What happens when you access a property that doesnβt exist directly on an object?
Answer
JavaScript walks up the prototype chain, checking each linked object in turn, until it finds the property or reaches the end of the chain (null), returningundefinedif it's never found. -
Is JavaScriptβs
classsyntax a different inheritance model from prototypes?Answer
No βclassis syntax sugar over the same prototype-based system; methods defined in a class body end up on the class's.prototype. -
Why is defining methods on
.prototypemore memory-efficient than defining them in the constructor?Answer
A 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.