Sub topic 14
Classes Are Built on Prototypes
This chapter assumes you already know constructor functions, the prototype property, and what new does, all covered in earlier chapters. ES2015 class syntax adds no new inheritance model. A class declaration creates a constructor function and places methods on that function's prototype object, the same layout you built by hand earlier. The syntax does change some defaults, and those changes are where the surprises come from.
What a class declaration creates
Here is a small class, followed by checks that show what the engine actually built.
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hi, I'm ${this.name}`;
}
get shout() {
return this.name.toUpperCase();
}
}
const ada = new Person('Ada');
console.log(typeof Person); // "function"
console.log(Object.getPrototypeOf(ada) === Person.prototype); // true
console.log(Person.prototype.constructor === Person); // true
console.log(Object.hasOwn(ada, 'name')); // true
console.log(Object.hasOwn(ada, 'greet')); // false
console.log(Object.hasOwn(Person.prototype, 'greet')); // true
console.log(ada.shout); // "ADA"
console.log(typeof Object.getOwnPropertyDescriptor(Person.prototype, 'shout').get); // "function"The pieces map onto the pre-class pattern like this:
- The
constructorblock becomes the body of the functionPerson. - Each method, including the getter, becomes a property of
Person.prototype. Instances share one copy of each method. Person.prototype.constructorpoints back toPerson, as it does for ordinary functions.new Person('Ada')creates an object whose[[Prototype]]isPerson.prototype, then runs the constructor body withthisbound to that object.
A hand-written equivalent
The following code builds nearly the same structure without class. The Object.defineProperty calls copy one detail that class syntax handles for you: methods are non-enumerable.
function Person(name) {
this.name = name;
}
Object.defineProperty(Person.prototype, 'greet', {
value: function () {
return `Hi, I'm ${this.name}`;
},
writable: true,
configurable: true,
enumerable: false
});
Object.defineProperty(Person.prototype, 'shout', {
get() {
return this.name.toUpperCase();
},
configurable: true,
enumerable: false
});
const ada = new Person('Ada');
console.log(ada.greet()); // "Hi, I'm Ada"
console.log(ada.shout); // "ADA"
for (const key in ada) console.log(key); // "name" onlyIf you write Person.prototype.greet = function () {...} instead, greet is enumerable and shows up in for...in loops over every instance. Class methods never do.
Where classes differ from constructor functions
The prototype layout is the same, but class syntax tightens several rules. Each of the following runs and prints the error it triggers.
// 1. Classes are not hoisted into usable form (temporal dead zone).
try {
new Early();
} catch (e) {
console.log(e.constructor.name); // "ReferenceError"
}
class Early {}
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hi, I'm ${this.name}`;
}
}
// 2. A class constructor cannot be called without new.
try {
Person('Ada');
} catch (e) {
console.log(e.constructor.name); // "TypeError"
}
// 3. Methods are not constructors.
const ada = new Person('Ada');
try {
new ada.greet();
} catch (e) {
console.log(e.constructor.name); // "TypeError"
}
// 4. Class bodies run in strict mode, so a detached method gets this === undefined.
const detached = ada.greet;
try {
detached();
} catch (e) {
console.log(e.constructor.name); // "TypeError" (reading name of undefined)
}
// 5. Methods are non-enumerable.
console.log(Object.keys(Person.prototype)); // []| Behavior | Constructor function | Class |
|---|---|---|
| Called without `new` | Runs, `this` is `undefined` (strict) or the global object (sloppy) | Throws `TypeError` |
| Use before declaration | Works (function declarations are hoisted) | Throws `ReferenceError` |
| Methods added to `prototype` | Enumerable when assigned directly | Non-enumerable |
| Methods usable with `new` | Yes, if written as `function` | No |
| Strict mode | Only if you opt in | Always |
| `typeof` | `"function"` | `"function"` |
Class fields are own properties, not prototype properties
Class fields (ES2022) look like they sit next to methods, but they are placed differently. A field is created on each instance when the constructor runs. A method lives once on the prototype.
class Counter {
count = 0; // field: own property on each instance
increment() { // method: on Counter.prototype
this.count += 1;
return this.count;
}
reset = () => { // arrow field: a new function per instance
this.count = 0;
};
}
const c = new Counter();
const d = new Counter();
console.log(Object.hasOwn(c, 'count')); // true
console.log(Object.hasOwn(c, 'increment')); // false
console.log(Object.hasOwn(c, 'reset')); // true
console.log(c.increment === d.increment); // true (shared)
console.log(c.reset === d.reset); // false (one per instance)
const r = c.reset;
c.increment();
r(); // this stays bound to c
console.log(c.count); // 0Arrow-function fields trade memory for convenience. Each instance carries its own function with this fixed to that instance, so the function is safe to detach. You pay for that with one allocation per instance per field, and subclasses cannot override the function through the prototype.
Common errors
- Expecting fields on the prototype.
Person.prototype.countisundefinedfor a field namedcount. Inspect an instance instead. - Treating classes as a separate type system.
typeofreturns"function"andinstanceofwalks the same prototype chain. Tools that patchPerson.prototypeaffect class instances exactly as they would affect constructor instances. - Relying on hoisting. Code that worked with function declarations breaks if you convert the function to a class and call it before its definition.
- Losing
thisin callbacks. Bind the method, wrap it in an arrow function at the call site, or use an arrow field when detaching it is the normal use.
Subclassing with extends and super builds on this same layout and is covered in the next chapter.
Exercise
Given class Box { size = 1; open() {} } and const b = new Box();, what do Object.hasOwn(b, 'size'), Object.hasOwn(b, 'open'), Object.keys(Box.prototype), and typeof Box produce, and why?
Show answer
true, false, [], and "function". The field size is created on each instance, so it is an own property of b. The method open lives on Box.prototype and is inherited. Class methods are non-enumerable, so Object.keys(Box.prototype) is empty. A class is a constructor function, so typeof reports "function".
Exercise
Rewrite class Temp { constructor(c) { this.c = c; } get f() { return this.c * 9 / 5 + 32; } } as a constructor function so that new Temp(100).f returns 212 and f stays non-enumerable. Name one behavior the rewrite still does not match.
Show answer
function Temp(c) { this.c = c; } Object.defineProperty(Temp.prototype, 'f', { get() { return this.c * 9 / 5 + 32; }, configurable: true, enumerable: false }); The rewrite can still be called without new (it does not throw), it is hoisted, and its body is not strict unless you add 'use strict'.