Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Classes vs constructor functions in JavaScript

78 What class syntax is sugar for, and what it is not

hard

Write the same type twice: once as a class, once as a function with methods on its prototype. Show that the instances are indistinguishable, then find the four things that genuinely differ — method enumerability, calling without new, the static side, and what new.target reports.

Stuck? Three hints, smallest first
  1. 1. Assigning to Fn.prototype.method creates an enumerable property. A class method is non-enumerable.
  2. 2. A class constructor refuses to be called without new. A function does not.
  3. 3. new.target is undefined in a plain call and the constructor in a new one.

The answer

const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };

class BusClass {
  static depot = 'Ojota';
  constructor(route) { this.route = route; }
  label() { return 'bus to ' + this.route; }
  get shortRoute() { return this.route.slice(0, 3); }
  static fromText(text) { return new BusClass(text.trim()); }
}

function BusFunction(route) { this.route = route; }
BusFunction.depot = 'Ojota';
BusFunction.prototype.label = function () { return 'bus to ' + this.route; };
BusFunction.fromText = function (text) { return new BusFunction(text.trim()); };

const a = new BusClass('Ojuelegba');
const b = new BusFunction('Ojuelegba');

const sameOutwardly = [
  a.label() === b.label(),
  a instanceof BusClass && b instanceof BusFunction,
  Object.getPrototypeOf(a) === BusClass.prototype && Object.getPrototypeOf(b) === BusFunction.prototype,
  typeof BusClass === typeof BusFunction,
];
const constructorLinks = [BusClass.prototype.constructor === BusClass, BusFunction.prototype.constructor === BusFunction];

const enumerability = [Object.keys(BusClass.prototype), Object.keys(BusFunction.prototype)];
const inForIn = [];
for (const key in b) inForIn.push(key);
const classInForIn = [];
for (const key in a) classInForIn.push(key);

class EmptyClass { constructor() {} }
function emptyFunction() {}
const withoutNew = [
  attemptName(() => BusClass('Ojota')),        // refused for being a class
  attemptName(() => EmptyClass()),             // refused even with a body that does nothing
  attemptName(() => emptyFunction()),          // just runs
  attemptName(() => BusFunction('Ojota')),     // fails for a different reason entirely
];
const strayGlobal = typeof globalThis.route;

let seen = 'never ran';
function Factory() { seen = new.target === undefined ? 'called' : 'constructed'; }
new Factory();
const withNew = seen;
Factory();
const withoutNewSeen = seen;

const staticSide = [
  Object.hasOwn(BusClass, 'depot'),
  Object.hasOwn(BusClass.prototype, 'depot'),
  BusClass.fromText('  Ojota  ').route,
];
const accessorOnPrototype = [
  typeof Object.getOwnPropertyDescriptor(BusClass.prototype, 'shortRoute').get,
  a.shortRoute,
];

console.log('indistinguishable:', sameOutwardly);
console.log('enumerable       :', enumerability);
console.log('without new      :', withoutNew);
console.log('new.target       :', withNew, '/', withoutNewSeen);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the instances are indistinguishable: same output, same chain, same typeof', sameOutwardly, [true, true, true, true]);
test('and both prototypes point back at their constructor', constructorLinks, [true, true]);
test('but class methods are non-enumerable, and hand-assigned ones are not', enumerability, [[], ['label']]);
test('so for...in over the function version lists the method as if it were data', [inForIn, classInForIn], [['route', 'label'], ['route']]);
test('a class refuses to be called without new whatever its body does, a function just runs', withoutNew.slice(0, 3), ['TypeError', 'TypeError', 'no error']);
test('the function version fails only because strict mode left it no this, so nothing reached the global', [withoutNew[3], strayGlobal], ['TypeError', 'undefined']);
test('new.target is how a plain function can tell the two apart', [withNew, withoutNewSeen], ['constructed', 'called']);
test('statics live on the constructor, never on the prototype', staticSide, [true, false, 'Ojota']);
test('and a class getter is a real accessor on the prototype', accessorOnPrototype, ['function', 'Oju']);

"Classes are just sugar" is close enough to be useful and wrong in four places, all of them visible above. Method enumerability is the one you feel first: hand-assigned prototype methods are enumerable, so for...in over an instance lists behaviour among the data — the fourth assertion — which is why old code is full of hasOwnProperty guards. Class methods are non-enumerable, and that alone removes a whole category of bug.

The new check is the second, and the two failures are not the same failure. A class is refused because it is a class — EmptyClass() throws with a body that does nothing at all. BusFunction('Ojota') is not refused; it runs, and only then throws because strict mode gave it no this to write route onto. In sloppy code that same call would have succeeded, writing a global route and returning undefined, so the caller gets nothing and the damage is elsewhere. new.target is the pre-class defence, and still the way a factory function can insist on one calling convention.

Two more differences that do not appear here. Class declarations are not hoisted the way function declarations are: the binding exists but is uninitialised, so touching it before the declaration is a ReferenceError rather than undefined. And a class body is always strict, whatever the surrounding code.

What is genuinely the same is worth as much as what differs. There is one object model underneath: a constructor function, a prototype object holding the shared methods, a constructor link back, instances whose [[Prototype]] is that object, and statics as plain properties of the function. extends is Object.setPrototypeOf applied to both the prototype and the constructor, which is why static members are inherited too.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.