Understanding Prototype Inheritance in JavaScript
In JavaScript, constructors can share methods via their prototype objects so that every instance created from the constructor gains access without duplicating code.
For example, to provide all instances of a constructor with an age calculation method:
function Human(yearBorn) {
this.yearBorn = yearBorn;
}
Human.prototype.computeAge = function () {
console.log(2099 - this.yearBorn);
};
const member = new Human(1990);
member.computeAge();
Embedding the method directly inside the constructor would cause each instance to carry its own copy, increasing memory use and reducing performance when many instances exist.
Every function in JavaScript possesses a prototype property referencing an object used for shared members. When a constructor is invoked with new, the resulting object links internally to that prototype.
An instance holds an internal reference—accessible via Object.getPrototypeOf() or historically as __proto__—pointing to its constructor's prototype. This linkage forms a chain: if a property or method is not found on the instance, the engine traverses the prototype chain upward until it locates the member or reaches the end at Object.prototype.
Key points:
- A function’s
prototypeattribute refers to an object that becomes the prototype for instances created vianew. - Instances have an implicit link (
[[Prototype]]) to the constructor’s prototype object. - The prototype chain enables inheritance; lookup proceeds from the instance toward
Object.prototype. - While a consturctor has its own
prototype, the instance’s prototype reference governs inheritance behavior.
Example checks:
console.log(Object.getPrototypeOf(member) === Human.prototype);
console.log(Human.prototype.isPrototypeOf(member));
console.log(Human.prototype.isPrototypeOf(Human));
The first comparison confirms that the instance’s prototype is the constructor’s prototype object. The isPrototypeOf calls verify whether a given object exists in another’s prototype chain; note that Human.prototype is not the prototype of Human itself, but of its instances.