JS Learning

Classes Basics

Object-Oriented ProgrammingSection 1 of 2intermediate

Topic Overview

Take your time to understand each concept. Practice with the examples below!

Classes in TypeScript are like cookie cutters - you define the shape once, then create as many cookies (objects) as you need! They bring object-oriented programming to JavaScript with extra type safety.

What are Classes? A class is a blueprint for creating objects. It defines what properties and methods every object created from it will have. Think of it as a factory that produces objects with consistent structure.

Class Components:

  • Properties:Data that each object will store
  • Constructor:Special method that runs when creating new objects
  • Methods:Functions that belong to the object
  • Access modifiers:Control who can access properties/methods

Access Modifiers - Who Can Touch What:

  • public:Anyone can access (default)
  • private:Only the class itself can access
  • protected:The class and its children can access
  • readonly:Can't be changed after initialization

Why Use Classes?

  • Organization:Group related data and functions together
  • Reusability:Create multiple objects with the same structure
  • Encapsulation:Hide internal details, expose only what's needed
  • Inheritance:Build new classes based on existing ones
  • Type safety:TypeScript ensures you use classes correctly

Real-World Examples:

  • User class:Properties like name, email, methods like login()
  • Product class:Properties like price, methods like applyDiscount()
  • Game character:Properties like health, methods like attack()
  • Shopping cart:Properties like items, methods like addItem()

Modern Features:

  • Getters/Setters:Control how properties are accessed
  • Static members:Belong to the class, not instances
  • Abstract classes:Templates that can't be instantiated
  • Parameter properties:Shorthand for constructor assignments

Example

// Basic class definition
class Person {
// Properties
private name: string;
private age: number;
public email: string;
// Constructor
constructor(name: string, age: number, email: string) {
this.name = name;
this.age = age;
this.email = email;
}
// Methods
public introduce(): string {
return `Hi, I'm ${this.name} and I'm ${this.age} years old.`;
}
public getAge(): number {
return this.age;
}
// Getter and Setter
get displayName(): string {
return this.name.charAt(0).toUpperCase() + this.name.slice(1);
}
set updateAge(newAge: number) {
if (newAge >= 0) {
this.age = newAge;
}
}
}
// Creating instances
const person1 = new Person("alice", 25, "alice@example.com");
const person2 = new Person("bob", 30, "bob@example.com");
console.log(person1.introduce());
console.log(`Display name: ${person1.displayName}`);
// Using setter
person1.updateAge = 26;
console.log(`Updated age: ${person1.getAge()}`);