class Is Sugar, and What It Hides
Everything a class does can be written with the constructor functions and prototypes from Unit 1, and seeing the two side by side removes the mystery.
A class declaration produces a function whose .prototype holds the methods. The constructor body is the old constructor function. What class adds is not new machinery but guard rails: it refuses to run without new, and its body is always strict.
EXERCISE
1The Same Thing, Written Twice
Put the class and the constructor function next to each other and every line maps onto a line you already know.
class arrived in 2015 and was immediately described as syntactic sugar. That phrase gets repeated a lot without being demonstrated, so here is the demonstration.
The constructor-function version, from Unit 1:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function () {
return `Hi, ${this.name}`;
};
Person.prototype.isAdult = function () {
return this.age >= 18;
};
The class version:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hi, ${this.name}`;
}
isAdult() {
return this.age >= 18;
}
}
Now check that the second really did produce the first:
console.log(typeof Person); // "function"
console.log(Person.prototype.greet); // [Function: greet]
console.log(Object.getOwnPropertyNames(Person.prototype));
// [ 'constructor', 'greet', 'isAdult' ]
const ada = new Person("Ada", 36);
console.log(Object.getPrototypeOf(ada) === Person.prototype); // true
console.log(ada.hasOwnProperty("greet")); // false
A class is a function. Its methods live on its .prototype. Instances link to that object. Every one of those facts is from Unit 1, unchanged.
Notice what is missing from that list of own property names: name and age are nowhere on the prototype. They only come into existence when a constructor runs and assigns to this, which is why two people can share one greet while each keeping their own name. This is the per-instance data against shared behaviour split from Unit 1, and a class enforces it by where you write things rather than by asking you to remember.
The mapping, stated once:
// class Person { ... } -> function Person() { ... }
// constructor(...) { ... } -> the body of that function
// greet() { ... } -> Person.prototype.greet = function () { ... }
// new Person(...) -> identical, the same four steps
This is why Unit 1 came first. If you had met class before the prototype chain, you would be learning two things and believing they were unrelated. They are one thing with two spellings.
Pro Tip: When a class does something you did not expect, rewrite the relevant part as a constructor function and a prototype assignment. Almost every surprising class behaviour becomes obvious in that form, because it is the form the engine is working with underneath.
EXERCISE
2What class Actually Adds
The syntax is tidier, and three genuine behaviour changes come with it that the old form cannot give you.
If it were only tidier syntax there would be no strong reason to prefer it. There are three real differences, and all three remove a category of mistake.
One: it refuses to run without new.
class Person {
constructor(name) {
this.name = name;
}
}
// Person("Ada");
// TypeError: Class constructor Person cannot be invoked without 'new'
The constructor-function version would have run happily, written to undefined in strict mode or to the global object in old scripts. This is the guard from Unit 1's last lesson, now enforced by the language rather than by a new.target check somebody remembered to write.
Two: the body is always strict, whatever the file is.
class Counter {
increment() {
undeclared = 1; // ReferenceError, even in a non-strict script
}
}
You cannot opt out. In a legacy codebase where most files are sloppy, a class body is an island of strictness.
Three: class declarations are not hoisted in a usable way.
// new Person(); ReferenceError: Cannot access 'Person' before initialization
class Person {}
// Compare with the old form, which does work:
new Animal();
function Animal() {}
The class binding exists from the top of the block but sits in the temporal dead zone until its declaration runs, exactly like let and const. This is a deliberate choice: using a class before you have defined it is almost always a mistake, and now it says so.
Methods are also non-enumerable, which matters for iteration:
class Person {
constructor(name) {
this.name = name;
}
greet() {
return "hi";
}
}
const ada = new Person("Ada");
for (const key in ada) console.log(key); // name (greet does not appear)
function Old(name) {
this.name = name;
}
Old.prototype.greet = function () {
return "hi";
};
const bob = new Old("Bob");
for (const key in bob) console.log(key); // name, then greet
The old form put greet on the prototype as an ordinary enumerable property, so for...in found it. Class methods are defined as non-enumerable, which is what you almost always want.
Pro Tip: "Sugar" is accurate about the machinery and slightly unfair about the value. The prototype mechanics are identical, and the guard rails are not: no silent missing
new, no accidental sloppy mode, no use before definition, no methods leaking intofor...in. Four bug categories closed for free, which is reason enough to prefer it.
EXERCISE
3Class Expressions, and Classes as Values
A class is a value like any other function, so it can be assigned, passed, returned and created on the fly.
Because a class is a function, everything you can do with a function you can do with a class.
A class expression, named or anonymous:
const Person = class {
constructor(name) {
this.name = name;
}
};
const Animal = class Creature {
describe() {
return Creature.name;
}
};
console.log(new Person("Ada").name); // Ada
console.log(new Animal().describe()); // Creature
// console.log(Creature); // ReferenceError: only visible inside
The inner name in the second case is visible only within the class body, which is the same rule named function expressions follow.
Passing a class into a function:
function makeAll(Cls, items) {
return items.map((item) => new Cls(item));
}
class Tag {
constructor(label) {
this.label = label;
}
}
const tags = makeAll(Tag, ["new", "sale"]);
console.log(tags.map((t) => t.label)); // [ 'new', 'sale' ]
Cls is a parameter holding a class. new Cls(item) runs the same four steps as always.
Returning a class from a function, which is how mixins are built:
function withTimestamp(Base) {
return class extends Base {
constructor(...args) {
super(...args);
this.createdAt = Date.now();
}
};
}
class Note {
constructor(text) {
this.text = text;
}
}
const TimestampedNote = withTimestamp(Note);
const n = new TimestampedNote("hello");
console.log(n.text); // hello
console.log(typeof n.createdAt); // number
console.log(n instanceof Note); // true
extends and super are the next lesson; this is here to show that a class created inside a function is an ordinary value with no restrictions. The pattern is called a mixin, and it is how behaviour gets shared without a deep inheritance tree.
One caution about mixins: each call to withTimestamp produces a brand new class, so calling it twice gives you two unrelated types. Create it once and reuse the result, rather than calling the factory at each use site.
And the check that proves there is nothing special going on:
class Person {}
console.log(typeof Person); // "function"
console.log(Person instanceof Function); // true
console.log(Object.getPrototypeOf(Person) === Function.prototype); // true
Treating classes as values is what separates code that uses classes from code that is stuck with them. A function that takes a class and returns a modified one lets you compose behaviour without inheriting five levels deep, and it works because a class was never anything more exotic than a function with a well-organised .prototype.
