Classes vs Prototypes
JavaScript is a prototype-based language, and class does not change that. A class creates a constructor function and puts its methods on that function’s prototype object, which is what developers did by hand before ES2015. Seeing both versions of the same code makes it clear what the class syntax is doing for you, and it helps when reading older code that uses the hand-written form.
The class version
Section titled “The class version”A Task has some text and a complete() method, and a RecurringTask extends it with a schedule:
class Task { constructor(text) { this.text = text; this.done = false; }
complete() { this.done = true; return `${this.text}: done`; }}
class RecurringTask extends Task { constructor(text, everyDays) { super(text); this.everyDays = everyDays; }
schedule() { return `${this.text}: every ${this.everyDays} days`; }}
const water = new RecurringTask('Water plants', 3);console.log(water.schedule());console.log(water.complete());This prints:
Water plants: every 3 daysWater plants: doneThe prototype version
Section titled “The prototype version”Without class, each part becomes a separate step:
- the constructor is an ordinary function that sets properties on
this - each method is assigned to the constructor’s
prototypeobject - the child constructor calls the parent constructor with
Task.call(this, ...)in place ofsuper(...) Object.setPrototypeOf()links the child’sprototypeobject to the parent’s, in place ofextends
function Task(text) { this.text = text; this.done = false;}
Task.prototype.complete = function () { this.done = true; return `${this.text}: done`;};
function RecurringTask(text, everyDays) { Task.call(this, text); this.everyDays = everyDays;}
Object.setPrototypeOf(RecurringTask.prototype, Task.prototype);
RecurringTask.prototype.schedule = function () { return `${this.text}: every ${this.everyDays} days`;};
const water = new RecurringTask('Water plants', 3);console.log(water.schedule());console.log(water.complete());This prints the same:
Water plants: every 3 daysWater plants: doneOlder code often writes RecurringTask.prototype = Object.create(Task.prototype) instead of calling Object.setPrototypeOf(). That replaces the prototype object, so it loses the constructor property unless the code sets it again. Call, Apply, and Bind Methods explains call().
The class builds the same structure
Section titled “The class builds the same structure”Inspecting the class version shows the prototype objects that it created. The data properties live on the instance, while the methods live on the prototypes, and the chain runs from RecurringTask.prototype to Task.prototype:
class Task { constructor(text) { this.text = text; } complete() {}}class RecurringTask extends Task { schedule() {}}const water = new RecurringTask('Water plants');
console.log(Object.keys(water));console.log(Object.hasOwn(water, 'complete'));console.log(Object.hasOwn(Task.prototype, 'complete'));console.log(Object.getPrototypeOf(water) === RecurringTask.prototype);console.log(Object.getPrototypeOf(RecurringTask.prototype) === Task.prototype);This prints:
[ 'text' ]falsetruetruetrueWhere they differ
Section titled “Where they differ”The two versions are close but not identical. A class:
- throws a
TypeErrorif it is called withoutnew, whereas a constructor function called withoutnewruns as a normal function, sothisis not a new object and the property assignments go astray or throw - runs its body in strict mode
- is not hoisted the way a function declaration is
- makes its methods non-enumerable, whereas a method assigned to
prototypeis enumerable and shows up infor...inloops - supports private
#fields andstaticblocks, which have no direct equivalent in the hand-written form
The enumerability difference is easy to see:
class TaskC { complete() {}}
function TaskP() {}TaskP.prototype.complete = function () {};
console.log(Object.getOwnPropertyDescriptor(TaskC.prototype, 'complete').enumerable);console.log(Object.getOwnPropertyDescriptor(TaskP.prototype, 'complete').enumerable);
for (const key in new TaskP()) { console.log(key);}This prints:
falsetruecompleteFor new code, use classes: they are shorter, and they avoid these pitfalls. Prototype Chain explains the lookup that both versions rely on.
Steve Griffith covers this topic in his video JavaScript Classes vs Prototypes.