Classes
| Fields | |
| Methods | |
| What this is | |
| new instances |
Fields
A class is a plan for objects that share the same shape. Fields store the data of each object, and every field needs a clear type.
Give fields initial values so objects start in a valid state before any method runs.
class User {
name: string = "Guest";
age: number = 0;
}
Methods
Methods are functions that live inside a class. They read field values and define what objects of that class can do.
Declare parameter types and a return type so bad calls are caught before the code runs.
class Greeter {
greet(name: string): string {
return "Hello " + name;
}
}
const greeter = new Greeter();
console.log(greeter.greet("Ada"));
What this is
Inside a method, this points to the current object. It lets the method read and update fields of the same object that received the call.
class Counter {
total: number = 0;
add(step: number): void {
this.total = this.total + step;
}
}
new instances
Use new to build an object from a class. Each call creates an independent object with its own copy of field values.
class User {
name: string = "Guest";
}
const first = new User();
const second = new User();
first.name = "Ada";
console.log(first.name);
console.log(second.name);
Next: Constructors
Article author: Arthur Isaev