Skip to content
jshacks.dev
Fundamentals

JavaScript Classes Are Functions and What the Sugar Hides

A JavaScript class is a constructor function with stricter rules, non-enumerable methods and a second prototype link for static inheritance. See what changes.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite, npm, TypeScript and Node.js logos.

The class keyword arrived in ES2015 and looks like a new object system. It is not one. Underneath it is the same constructor function and prototype arrangement that JavaScript has always had, with syntax that makes the common pattern shorter and safer, and a few rules added that a hand-written version never had. Knowing exactly what the sugar covers helps in two directions: you can read older prototype code without confusion, and you can predict the surprises that classes still have, such as methods that lose this when passed around. This post compares a class with its hand-written equivalent in runnable code on Node.js 24, lists the differences that matter, and covers extends, new.target and the cases where a class is the wrong tool. The chain it builds is drawn in the post on the prototype chain, and the names involved are sorted out in the post on prototype and __proto__.

A class and its hand-written twin

Write the same thing both ways and compare.

JavaScript
class Counter {
  constructor(start = 0) {
    this.count = start;
  }
  increment() {
    this.count += 1;
    return this;
  }
}

function LegacyCounter(start = 0) {
  this.count = start;
}
LegacyCounter.prototype.increment = function () {
  this.count += 1;
  return this;
};

const a = new Counter(5).increment();
const b = new LegacyCounter(5).increment();

console.log(a.count, b.count);
console.log(typeof Counter, typeof LegacyCounter);
console.log(Object.getPrototypeOf(a) === Counter.prototype);
console.log(Counter.prototype.constructor === Counter);
console.log(Counter.name, Counter.length);
console.log(Object.getOwnPropertyNames(Counter.prototype));
Text
6 6
function function
true
true
Counter 0
[ 'constructor', 'increment' ]

The two behave the same for the basic case. A class is a function, its prototype holds the method, prototype.constructor points back and instances link to the prototype. The constructor body of the class became the function body, and the increment method became an entry on Counter.prototype. Everything else is a difference of rules.

Differences you will actually meet

The first difference is that a class cannot be called without new.

JavaScript
class Invoice {
  constructor() {
    this.total = 0;
  }
}

try {
  Invoice();
} catch (error) {
  console.log(error.name + ": " + error.message);
}

const legacyInvoice = new Function("this.total = 0;");

legacyInvoice();
console.log(globalThis.total);
delete globalThis.total;
Text
TypeError: Class constructor Invoice cannot be invoked without 'new'
0

The class throws a clear error. The legacy function, built with the Function constructor so that it runs in sloppy mode, ran without complaint, and total appeared on the global object, where this falls back to. A forgotten new leaks globals in a sloppy script, and the class form turns that into an immediate error. In strict code a plain constructor function fails too, but with a less helpful Cannot set properties of undefined.

The second difference is that methods are not enumerable, and class bodies are always strict.

JavaScript
class Greeter {
  hello() {
    return "hello " + this?.name;
  }
}

function LegacyGreeter() {}
LegacyGreeter.prototype.hello = function () {
  return "hello";
};

const keys = [];
for (const key in new Greeter()) keys.push(key);
for (const key in new LegacyGreeter()) keys.push(key);

console.log(keys);
console.log(Object.keys(Greeter.prototype), Object.keys(LegacyGreeter.prototype));

const detached = new Greeter().hello;
console.log(detached());
Text
[ 'hello' ]
[] [ 'hello' ]
hello undefined

A for...in loop over a class instance does not list its methods, while the legacy prototype method shows up. That is the descriptor difference from the post on property descriptors: class methods are non-enumerable. And the detached method ran in strict mode with this undefined, so the optional chain returned undefined instead of reading a global.

Not hoisted for use

A function declaration can be called before its line. A class declaration is hoisted like let, which means it is in its dead zone until its line runs.

JavaScript
console.log(typeof legacyFactory);

try {
  new Early();
} catch (error) {
  console.log(error.name + ": " + error.message);
}

function legacyFactory() {}

class Early {}
console.log(typeof Early);
Text
function
ReferenceError: Cannot access 'Early' before initialization
function

The function declaration was usable early. The class threw, with the message from the post on the temporal dead zone. A module should declare its classes before the code that instantiates them.

Inheritance with extends links the prototype objects for instance methods, and also links the constructors, so static members and super calls work.

JavaScript
class Base {
  static kind = "base";
  static describe() {
    return "I am " + this.name;
  }
  hello() {
    return "base hello";
  }
}

class Derived extends Base {
  hello() {
    return "derived over " + super.hello();
  }
}

const d = new Derived();

console.log(Object.getPrototypeOf(Derived.prototype) === Base.prototype);
console.log(Object.getPrototypeOf(Derived) === Base);
console.log(Derived.kind, Derived.describe());
console.log(d.hello());
Text
true
true
base I am Derived
derived over base hello

The static describe was inherited through the constructor link, and this.name was Derived, because the call had Derived before the dot. The super.hello() call looked up hello on the parent prototype. A hand-written version has to set both links manually, with Object.setPrototypeOf(Derived, Base) for statics and Derived.prototype = Object.create(Base.prototype) for instances, and forgetting the first is a common source of missing statics.

Subclassing built-ins and calling super

A class can extend a built-in such as Array or Error, which a legacy constructor could not do reliably because the built-in creates its own object. In a derived constructor, super() must run before this is used.

JavaScript
class Stack extends Array {
  peek() {
    return this.at(-1);
  }
}

const stack = Stack.from([1, 2, 3]);
console.log(stack.peek(), stack instanceof Array, stack.map((n) => n * 2) instanceof Stack);

class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

const error = new ValidationError("email", "bad address");
console.log(error instanceof Error, error.name, error.field, error.message);

class Broken extends Object {
  constructor() {
    try {
      this.x = 1;
    } catch (e) {
      console.log(e.name + ": " + e.message);
    }
    super();
  }
}

new Broken();
Text
3 true true
true ValidationError email bad address
ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

The Stack subclass kept array behavior, and map returned another Stack, because built-in methods create results through the subclass constructor. The error subclass behaves as expected, and the post on custom error classes covers the details. The last example shows the rule that touching this before super() throws, since in a derived class the object does not exist until the parent constructor creates it.

new.target

Inside a constructor, new.target is the constructor that new was applied to, or undefined for a plain call. It lets a base class refuse direct instantiation.

JavaScript
class Shape {
  constructor() {
    if (new.target === Shape) {
      throw new TypeError("Shape is abstract");
    }
  }
}

class Square extends Shape {}

console.log(new Square() instanceof Shape);

try {
  new Shape();
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
true
TypeError: Shape is abstract

JavaScript has no abstract keyword, and this is the usual substitute. The check sees Square when a subclass is constructed, since new.target is the outermost constructor.

Fields live on the instance, methods on the prototype

Class fields are new syntax, and they are created on each instance during construction. That is a different place from methods, and the difference shows up in memory and in this behavior. An arrow function stored in a field is a fresh function per instance and keeps this bound, while a normal method is one shared function.

JavaScript
class Button {
  label = "Save";
  onClickArrow = () => this.label;
  onClickMethod() {
    return this.label;
  }
}

const one = new Button();
const two = new Button();

console.log(Object.hasOwn(one, "label"), Object.hasOwn(one, "onClickMethod"));
console.log(one.onClickArrow === two.onClickArrow);
console.log(one.onClickMethod === two.onClickMethod);

const { onClickArrow } = one;
console.log(onClickArrow());
Text
true false
false
true
Save

The label and the arrow are own properties, and the method is shared. The detached arrow still works, which is why event handlers are often written as arrow fields. The cost is one function object per instance, which is negligible for a few buttons and worth avoiding for a model class with thousands of instances. The post on the this keyword lists the other fixes for a lost receiver.

A test that pins the behavior

The differences above are worth a short test in any codebase that is migrating constructor functions to classes, because the migration changes three behaviors at once: calling without new, enumeration and this in detached methods.

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

class Cart {
  items = [];
  add(item) {
    this.items.push(item);
    return this;
  }
}

test("a class refuses to run without new", () => {
  assert.throws(() => Cart(), TypeError);
});

test("methods are not enumerable", () => {
  assert.deepEqual(Object.keys(Cart.prototype), []);
  assert.deepEqual(Object.keys(new Cart().add("a")), ["items"]);
});

test("a detached method has no this", () => {
  const { add } = new Cart();
  assert.throws(() => add("a"), TypeError);
});

Run it with node --test on Node.js 24. The second test records that instance data is an own property while the method is not, which matters for serialization with JSON.stringify() and for object spread, neither of which sees prototype members. The third records the detached-method behavior that surprises people moving from older code.

When a class is the wrong tool

A class is not a separate type system. Instances are ordinary objects, methods are shared through the prototype, and this is still decided by the call. Private fields, declared with #, are new and have no legacy equivalent, and they are explained in the post on private class fields. Public class fields, written as count = 0;, are created on each instance and are not shared, which differs from a prototype property.

For code that is only a bag of functions, a module with exported functions is simpler than a class with no state. For code with state and a handful of methods, a class is clear. For deep hierarchies, composition is usually easier to change.

The behavior is defined in the specification under class definitions, and MDN's classes guide lists every member form.

Also inPatterns
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.