Reading history

JavaScript Prototypes and Prototypal Inheritance

5 min read 0 views

Learn how JavaScript prototypes work: the prototype chain, Object.create, own vs inherited properties, constructor functions and how classes use prototypes.

Why can you call .toUpperCase() on any string, or .push() on any array, when you never wrote those methods? The answer is prototypes. Objects in JavaScript can borrow from a “parent” object: when you ask for a property that an object does not have itself, the engine quietly checks its parent, then the parent’s parent, and so on. Even the class keyword is built on this mechanism, so understanding it explains how inheritance really works.

In this lesson you will learn

  • What a prototype is and how property lookup follows the chain
  • Object.create and Object.getPrototypeOf
  • Own versus inherited properties
  • Constructor functions and .prototype
  • How class and extends map onto prototypes

This lesson builds on JavaScript Classes and the this keyword.

Prototypes and Constructor Functions

// Every object has a hidden link to a prototype
const device = {
  needsPower: true,
  describe() { return `${this.model} needs power: ${this.needsPower}`; },
};
const laptop = Object.create(device);      // laptop's prototype is device
laptop.model = "Laptop X1";

console.log(laptop.describe());              // found on the prototype
console.log(Object.hasOwn(laptop, "model"));      // own property
console.log(Object.hasOwn(laptop, "needsPower")); // inherited, not own
console.log(Object.getPrototypeOf(laptop) === device);

// Constructor functions share methods through .prototype
function Book(title, pages) {
  this.title = title;
  this.pages = pages;
}
Book.prototype.isLong = function () { return this.pages > 300; };

const b1 = new Book("Short Stories", 120);
const b2 = new Book("Big Novel", 640);
console.log(b1.isLong(), b2.isLong());
console.log(b1.isLong === b2.isLong);   // one shared function

Output

Laptop X1 needs power: true
true
false
true
false true
true
  • Object.create(device) makes a new empty object whose prototype is device.
  • laptop.describe() is not on laptop, so JavaScript looks in its prototype and finds it there. Inside, this is still laptop, so this.model is “Laptop X1”.
  • Object.hasOwn tells you whether a property lives on the object itself (true for model) or is inherited (false for needsPower).
  • Before classes existed, you wrote a constructor function and called it with new. Methods placed on Book.prototype are shared by every book, so b1.isLong === b2.isLong: there is one copy in memory, not one per object.

Classes Are Prototypes Underneath

// class syntax is built on prototypes
class Shape {
  constructor(name) { this.name = name; }
  area() { return 0; }
  toString() { return `${this.name} with area ${this.area().toFixed(2)}`; }
}
class Circle extends Shape {
  constructor(r) { super("Circle"); this.r = r; }
  area() { return Math.PI * this.r ** 2; }
}
const c = new Circle(2);
console.log(String(c));

// The prototype chain
console.log(Object.getPrototypeOf(c) === Circle.prototype);
console.log(Object.getPrototypeOf(Circle.prototype) === Shape.prototype);
console.log(Object.getPrototypeOf(Shape.prototype) === Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype));

// Methods live on the prototype, data lives on the instance
console.log(Object.keys(c));
console.log(typeof Circle);              // classes are functions

Output

Circle with area 12.57
true
true
true
null
[ 'name', 'r' ]
function
  • Methods defined in a class body are stored on ClassName.prototype, exactly like the Book example.
  • extends links Circle.prototype to Shape.prototype. When String(c) calls toString, it is found on Shape.prototype, but its call to this.area() finds the overriding version on Circle.prototype first.
  • Every chain ends at Object.prototype, whose own prototype is null. That is where shared methods such as hasOwnProperty come from.
  • Object.keys(c) lists only own data (name, r); methods are not copied onto instances.
  • typeof Circle is “function”: a class is a special constructor function.

Useful Prototype Tools

CodePurpose
Object.getPrototypeOf(obj)Read an object’s prototype
Object.create(proto)Make an object with a chosen prototype
Object.hasOwn(obj, "key")Check for an own property
obj instanceof ClassIs Class.prototype anywhere in the chain?
"key" in objOwn or inherited property exists
Object.create(null)An object with no prototype at all, a clean dictionary

Common Mistakes

  1. Adding methods inside the constructor (this.isLong = function…), which creates a new copy for every object.
  2. Using arrow functions on .prototype; they do not receive the instance as this.
  3. Modifying built-in prototypes such as Array.prototype, which can clash with libraries and future JavaScript features.
  4. Confusing __proto__ and .prototype: .prototype belongs to constructor functions and becomes the prototype of objects they create.

Practice Exercises

Exercise 1. Create a Rectangle class extending Shape (from the example) with width and height, and print it.

Show answer
class Rectangle extends Shape {
  constructor(w, h) { super("Rectangle"); this.w = w; this.h = h; }
  area() { return this.w * this.h; }
}
console.log(String(new Rectangle(3, 4)));  // Rectangle with area 12.00

Exercise 2. What does [] instanceof Object print, and why?

Show answer

true. An array’s chain is Array.prototype → Object.prototype → null, and Object.prototype is in it.

Frequently Asked Questions

Should I write constructor functions or classes?

Use classes in new code. They are clearer and safer (they must be called with new), and they produce the same prototype structure. Knowing constructor functions helps you read older code.

Is prototype inheritance slower than copying methods?

No. Engines optimise prototype lookups heavily, and sharing one method among many objects saves memory.

Summary

  • Each object links to a prototype; missing properties are looked up along the chain.
  • Shared methods live on the prototype, data lives on each object.
  • class and extends are a clearer syntax for prototype chains.
  • Every chain ends at Object.prototype, then null.

Next: Iterators and Generators.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *