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.
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
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)- 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
walkfunction onanimal;thispoints 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.setPrototypeOf | The standard way to read/write that link |
obj.__proto__ | Legacy accessor for the same link (avoid in new code) |
Fn.prototype | A property on functions: the object that will become the [[Prototype]] of instances created with new Fn() |
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:
- Creates a new empty object.
- Sets its
[[Prototype]]toPerson.prototype. - Calls
Personwiththisbound to the new object. - Returns the object (unless the function explicitly returns a different object).
Inheritance the pre-ES6 way:
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
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; // trueDifferences 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
| Approach | Truly private? | Notes |
|---|---|---|
#field | Yes | Standard, enforced by the engine; #x in obj checks presence |
_field convention | No | Just a naming hint |
| Closures | Yes | Per-instance functions (more memory) |
TypeScript private | Compile-time only | Erased at runtime |
Checking types and properties
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); // trueObjects without prototypes
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:
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.
- 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.
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.