Prototypes & Classes

JavaScript's prototype-based inheritance — the prototype chain, __proto__ vs prototype, constructor functions, Object.create, how ES6 classes desugar, private fields, static members, and mixins.

Intermediate 3 min readLesson 5 of 12 Interview Q&A

JavaScript doesn't have classes in the Java sense. It has objects that link to other objects. When you read a property an object doesn't have, the engine looks it up on the object's prototype, then that object's prototype, and so on — the prototype chain. ES6 class syntax is a cleaner way to set up exactly these links.

The prototype chain

JavaScript
const animal = { eats: true, walk() { return `${this.name} walks`; } };
const rabbit = Object.create(animal);      // rabbit's prototype is animal
rabbit.name = "Bunny";
rabbit.jumps = true;

rabbit.jumps;        // true   (own property)
rabbit.eats;         // true   (found on animal)
rabbit.walk();       // "Bunny walks" — method from the prototype, this = rabbit
rabbit.toString;     // found on Object.prototype
rabbit.fly;          // undefined — reached the end of the chain (null)
[[Prototype]]rabbitname, jumpsanimaleats, walk()Object.prototypetoString, hasOwnProperty…null
  • Reads walk the chain. Writes always create or update an own property (shadowing the prototype's), unless a setter is found.
  • Methods are shared: there's one walk function on animal; this points to whichever object it was called on.
  • Long chains make missing-property lookups slower; engines cache lookups with inline caches (V8 internals).

__proto__ vs prototype (the confusing part)

What it is
obj.[[Prototype]]The internal link every object has to its prototype
Object.getPrototypeOf(obj) / Object.setPrototypeOfThe standard way to read/write that link
obj.__proto__Legacy accessor for the same link (avoid in new code)
Fn.prototypeA property on functions: the object that will become the [[Prototype]] of instances created with new Fn()
JavaScript
function Person(name) { this.name = name; }
Person.prototype.greet = function () { return `Hi, ${this.name}`; };

const ada = new Person("Ada");
Object.getPrototypeOf(ada) === Person.prototype;   // true
Person.prototype.constructor === Person;           // true
ada.greet();                                       // "Hi, Ada"

Constructor functions and new

new Person("Ada") does four things:

  1. Creates a new empty object.
  2. Sets its [[Prototype]] to Person.prototype.
  3. Calls Person with this bound to the new object.
  4. Returns the object (unless the function explicitly returns a different object).

Inheritance the pre-ES6 way:

JavaScript
function Employee(name, title) {
  Person.call(this, name);                                   // super constructor
  this.title = title;
}
Employee.prototype = Object.create(Person.prototype);        // link prototypes
Employee.prototype.constructor = Employee;
Employee.prototype.describe = function () { return `${this.greet()} — ${this.title}`; };

ES6 classes: the same thing, nicer

JavaScript
class Person {
  static count = 0;                    // static field (on the class itself)
  #ssn;                                // truly private field (runtime-enforced)

  constructor(name, ssn) {
    this.name = name;                  // own property per instance
    this.#ssn = ssn;
    Person.count++;
  }

  greet() { return `Hi, ${this.name}`; }        // goes on Person.prototype (shared)
  get initials() { return this.name.split(" ").map((p) => p[0]).join(""); }
  #mask() { return "***-**-" + this.#ssn.slice(-4); }   // private method
  get maskedSsn() { return this.#mask(); }

  static compare(a, b) { return a.name.localeCompare(b.name); }
}

class Employee extends Person {
  constructor(name, ssn, title) {
    super(name, ssn);                  // must call before using 'this'
    this.title = title;
  }
  greet() { return `${super.greet()}, ${this.title}`; }   // override + super call
}

const e = new Employee("Ada Lovelace", "123-45-6789", "Engineer");
e.greet();                 // "Hi, Ada Lovelace, Engineer"
e.initials;                // "AL"
e.#ssn;                    // SyntaxError: private field
typeof Employee;           // "function" — classes are functions
Object.getPrototypeOf(Employee.prototype) === Person.prototype;   // true

Differences from constructor functions: class bodies are strict mode; classes must be called with new; class declarations are hoisted but in the TDZ; methods are non-enumerable; extends can subclass built-ins like Array and Error properly.

Privacy options

ApproachTruly private?Notes
#fieldYesStandard, enforced by the engine; #x in obj checks presence
_field conventionNoJust a naming hint
ClosuresYesPer-instance functions (more memory)
TypeScript privateCompile-time onlyErased at runtime

Checking types and properties

JavaScript
e instanceof Employee;               // true — is Employee.prototype on e's chain?
e instanceof Person;                 // true
Object.hasOwn(e, "name");            // true  (own property)
Object.hasOwn(e, "greet");           // false (inherited)
"greet" in e;                        // true  (anywhere on the chain)
Person.prototype.isPrototypeOf(e);   // true

Objects without prototypes

JavaScript
const dict = Object.create(null);    // no Object.prototype: no toString, no __proto__ quirks
dict["__proto__"] = "safe";          // just a normal key
// Prefer Map for dictionaries with arbitrary keys anyway.

Composition and mixins

JavaScript allows single inheritance only, but functions can compose behaviour:

JavaScript
const Serializable = (Base) => class extends Base {
  toJSON() { return { ...this }; }
};
const Timestamped = (Base) => class extends Base {
  createdAt = new Date();
};

class Document extends Serializable(Timestamped(Object)) {}

As in any language, prefer composition (objects holding helpers) over deep hierarchies.

Key takeaways
  • Objects link to prototypes; property reads walk the chain up to null; writes create own properties.
  • Fn.prototype becomes the [[Prototype]] of objects created by new Fn().
  • Classes are syntax over constructor functions and prototypes, with strict mode, super and #private fields.
  • Methods live on the prototype and are shared; this is the calling object.
  • Guard against prototype pollution; use Map or Object.create(null) for dictionaries.
Interview questions
QHow does prototypal inheritance differ from classical inheritance?medium

In classical inheritance (Java), classes are blueprints and instances are copies of their structure, fixed at compile time. In JavaScript, objects inherit directly from other objects at runtime: missing properties are delegated along the prototype chain. ES6 classes are syntax over this mechanism. Prototypes can be changed at runtime, and objects can be created with any prototype via Object.create.

QWhat does the new keyword do?easy

It creates a new object, sets its prototype to the constructor's prototype property, calls the constructor with this bound to the new object, and returns that object unless the constructor explicitly returns another object.