Classes: syntax and what they add
A class in JavaScript is the shorter way to write the constructor function and the prototype method of the previous lesson. It creates the same kind of object, inherits the same way, and keeps the same prototype chain. What it adds is a body of rules that the older form left to the programmer.
This lesson writes a class, checks that its methods live on the prototype, calls one without new to see what the syntax refuses, and reads the binding before its declaration. Inheritance comes two lessons later, and it is built on exactly these objects.
The class syntax
The declaration holds a constructor and one or more methods written without the function keyword. A method is a function that takes the receiver as this, and new Point(3, 4) runs the constructor on a fresh object. Nothing else is needed, and typeof still answers function for the class itself.
The file class.mjs:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
distance() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
}
const p = new Point(3, 4);
console.log('the fields:', p.x, p.y);
console.log('the method:', p.distance());
console.log('the type is still object:', typeof p);
console.log('the class name answers:', p.constructor.name);
console.log('one method for all instances:', p.distance === new Point(6, 8).distance);
node class.mjs
the fields: 3 4
the method: 5
the type is still object: object
the class name answers: Point
one method for all instances: true
The instance holds the two fields and reads the method through its prototype. The class name is available as constructor.name, which is the first thing a log line shows. The last line proves that the two instances share one method, so a class is not a factory of closures.
What class adds
The methods of a class are non-enumerable, which means an instance has only its fields in a list of keys and a for-in loop does not walk into the methods. The same method added to the prototype of a function is enumerable, because an assignment creates an enumerable property. That single difference is why a class is the safer default for data that will be copied or serialised.
The file prototype.mjs:
class Counter {
constructor() {
this.count = 0;
}
bump() {
return (this.count += 1);
}
}
function OldCounter() {
this.count = 0;
}
OldCounter.prototype.bump = function bump() {
return (this.count += 1);
};
const c = new Counter();
c.bump();
console.log('the own keys of an instance:', Object.keys(c).join(','));
console.log('the method is on the prototype:', Object.hasOwn(Counter.prototype, 'bump'));
const seenClass = [];
for (const key in c) {
seenClass.push(key);
}
console.log('a for-in loop over an instance:', seenClass.join(','));
const seenOld = [];
for (const key in new OldCounter()) {
seenOld.push(key);
}
console.log('the same loop over a function instance:', seenOld.join(','));
console.log('a class method is not enumerable:', Object.keys(Counter.prototype).length);
console.log('a function method is:', Object.keys(OldCounter.prototype).join(','));
node prototype.mjs
the own keys of an instance: count
the method is on the prototype: true
a for-in loop over an instance: count
the same loop over a function instance: count,bump
a class method is not enumerable: 0
a function method is: bump
Two instances of the same shape, one count and two different loops. The class version kept the method out of the list and out of the loop, and the function version let both see it. A copy made with the spread or with Object.assign therefore takes the fields of a class instance and none of its behaviour, which is worth knowing before copying one.
A class cannot be called
Calling a class without new throws, and the message says why. The body of a class is also strict code whether or not the file is, so a method that is taken out of its object loses this and fails on the first field it reads. Both rules turn a mistake that used to be silent into an error at the call site.
The file nonew.mjs:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
return this.x + this.y;
}
}
try {
const p = Point(1, 2);
console.log('called without new:', p);
} catch (error) {
console.log(error.name + ': ' + error.message);
}
const p = new Point(1, 2);
const detached = p.sum;
try {
detached();
} catch (error) {
console.log('a detached method:', error.name + ': ' + error.message);
}
console.log('but the method itself is a function:', typeof Point.prototype.sum);
node nonew.mjs
TypeError: Class constructor Point cannot be invoked without 'new'
a detached method: TypeError: Cannot read properties of undefined (reading 'x')
but the method itself is a function: function
The first error replaced the silent write to the global object that the previous lesson showed. The second is the detached method: the function is fine, and the call has no receiver, so this is undefined. The last line reads the method from the prototype to show that the function itself is unharmed and only the call was wrong.
Declared, not hoisted
A function declaration is usable before the line that declares it, and a class is not: the name exists in the block from the start, but it is uninitialised until the declaration runs, and a use before that point throws a ReferenceError. The behaviour is the one let and const have, which is the shape a class declaration takes.
The file hoisting.mjs:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
console.log('a class is a function:', typeof Point);
console.log('its name is the class name:', Point.name);
try {
new Late(1);
} catch (error) {
console.log('before its declaration:', error.name + ': ' + error.message);
}
class Late {
constructor(n) {
this.n = n;
}
}
console.log('after the declaration:', new Late(1).n);
node hoisting.mjs
a class is a function: function
its name is the class name: Point
before its declaration: ReferenceError: Cannot access 'Late' before initialization
after the declaration: 1
The error says the name cannot be accessed before its initialisation, which is the same message a const gives. The program is fine after the declaration, and the first two lines show that a class is an ordinary function value with a name. The practical rule: put the classes at the top of the file, or in a module that is imported first.
Exercises
- Add a static method to the class in class.mjs and call it. Where does the method live, on the class or on an instance?
- List the own property names of Counter.prototype in prototype.mjs. Which two names are there, and why is the constructor one of them?
- Write the class of class.mjs as a function constructor and compare the two versions with Object.keys. Which version lists the methods?
- Take bump out of the Counter instance in prototype.mjs and call it. What is the error, and what does bind change about it?
- Move the class in hoisting.mjs to the end of the file and put the call before it inside a function that runs after the declaration. Does the error still happen?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a class declaration create?
Answer
A constructor function with a prototype
The class is a function whose prototype holds the methods, which is what new needs.
-
Where do the methods of a class live?
Answer
On the prototype of the class
One copy on the prototype is what every instance reads through the chain.
-
Why does a for-in loop over a class instance skip its methods?
Answer
Class methods are not enumerable
A class defines its methods as non-enumerable, while an assignment to a prototype makes an enumerable one.
-
What happens when a class is used before its declaration?
Answer
A ReferenceError, because the binding is not initialised yet
The name is in the temporal dead zone until the declaration runs.
-
What does this program print?
class P { constructor(x) { this.x = x; } get double() { return this.x * 2; } } console.log(new P(3).double);Answer
6
The getter runs on the instance and reads the field the constructor set.
-
What does this program print?
class P { go() { return "go"; } } const p = new P(); console.log(Object.keys(p).length, Object.keys(P.prototype).length);Answer
0 0
The instance has no fields and the method is non-enumerable, so both lists are empty.
-
What does this program print?
class P { constructor(n) { this.n = n; } } const p = new P(4); console.log(typeof P, p instanceof P);Answer
function true
A class is a function value, and the instance carries the prototype of the class in its chain.
-
What does this program print?
class Counter { count = 0; bump() { this.count += 1; return this.count; } } const c = new Counter(); c.bump(); console.log(c.count, Object.keys(c).join(","));Answer
1 count
The field is own and the method is not, so the list of keys holds the field alone.
-
What happens when this module runs?
class P {} const p = P();Answer
It throws a TypeError: Class constructor P cannot be invoked without new
A class may only be constructed with new, and the message names the class.
-
What happens when this module runs?
class P { constructor() { this.n = 1; } go() { return this.n; } } const p = new P(); const go = p.go; go();Answer
It throws a TypeError, because this is undefined
The detached call has no receiver, and the body of a class is strict code.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev