Sub topic 1
Declaring a Class
Prerequisites
This chapter assumes you know JavaScript variables, functions, and arrow functions. It also assumes you can read and write object properties, have a basic idea of what this means, and can run code in Node.js or a browser console.
Declaring a Class and Creating Instances
A class is a template for objects that share the same structure and behavior. The constructor method runs once for each object you create with new. Inside the constructor, this refers to the new instance, so you assign instance properties to this. Instance methods go in the class body and are available on every instance.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
distanceTo(other) {
return Math.hypot(this.x - other.x, this.y - other.y);
}
}
const a = new Point(0, 0);
const b = new Point(3, 4);
console.log(a.distanceTo(b)); // 5Methods in the class body are not separated by commas. Writing commas between them is a common syntax error for people used to object literals.
What Classes Really Are: Functions and Prototypes
A class is a special kind of function. Its methods are stored once on Point.prototype, and every instance reaches them through the prototype chain. The instance itself holds only the data set in the constructor.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
distanceTo(other) {
return Math.hypot(this.x - other.x, this.y - other.y);
}
}
const p = new Point(1, 2);
console.log(typeof Point); // "function"
console.log(Object.getPrototypeOf(p) === Point.prototype); // true
console.log(Object.hasOwn(p, 'distanceTo')); // false
console.log(Object.hasOwn(Point.prototype, 'distanceTo')); // trueHow Classes Differ from Functions
Classes behave differently from plain constructor functions in three ways:
| Behavior | Function declaration | Class declaration |
|---|---|---|
| Use before definition | Works (fully hoisted) | ReferenceError (temporal dead zone) |
| Call without `new` | Runs, `this` may be wrong | TypeError |
| Strict mode | Opt-in | Always on in the class body |
The temporal dead zone (TDZ) is the stretch of code before the declaration runs. The class name exists in that stretch but cannot be used yet.
try {
new Foo();
} catch (err) {
console.log(err.name); // "ReferenceError"
}
class Foo {}
try {
Foo();
} catch (err) {
console.log(err.name); // "TypeError"
}Exercise
After running const p = new Point(1, 2), why does Object.hasOwn(p, 'distanceTo') return false while p.distanceTo still works?
Show answer
The method is defined once on Point.prototype, not on each instance. When you access p.distanceTo, JavaScript does not find it on p, so it follows the prototype chain and finds it on Point.prototype.
Exercise
What error do you get when you call a class without new, and what error do you get when you use it before its declaration?
Show answer
Calling it without new throws a TypeError. Using it before its declaration throws a ReferenceError, because the class is in the temporal dead zone.