Classes (class)
A class is a template that describes how to create objects that share the same data and methods.
A class groups data and behavior in one place. You write it with the word class, a PascalCase name and a { } block with its members.
The class is not an object yet: it is the mold. With new you create an instance, and each instance has its own data. Methods are declared once and every instance shares them.
In the course you will see export class Cart { from lesson 01.07. export lets other files import it. Later, NestJS organizes almost everything with classes: services, controllers, modules.
Classes exist in JavaScript. The type annotations inside them (like items: string[]) are checked by tsc and are gone when Node runs the code.
class Dog {
name = "Rex";
bark() {
return `${this.name}: woof`;
}
}
Reach for it when: you need several objects with the same shape and behavior, or when a framework like NestJS asks for a class.
Examples
Common mistake
class Cart {
total = 0;
}
const cart = Cart();
console.log(cart.total);Why: A class cannot be called like a function: you must create the instance with `new`.
How to write it: Write new Cart().
