JavaScript Classes Basics
Classes are blueprints for creating objects with shared properties and methods.
Basic Syntax
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}!`;
}
}
let john = new Person("John", 25);
console.log(john.greet()); // "Hello, I'm John!"
constructor— Initializes the object when you usenewthis— Refers to the current instance- Methods are shared across all instances
The Constructor
Sets up initial state with default values:
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.mileage = 0;
}
drive(miles) { this.mileage += miles; return this; }
}
let myCar = new Car("Toyota", "Camry", 2020);
myCar.drive(100);
console.log(myCar.mileage); // 100
Method Chaining
Return this to chain method calls:
class Calculator {
constructor() { this.value = 0; }
add(n) { this.value += n; return this; }
subtract(n) { this.value -= n; return this; }
multiply(n) { this.value *= n; return this; }
getResult() { return this.value; }
}
let result = new Calculator().add(10).subtract(3).multiply(2).getResult();
console.log(result); // 14
Class Properties
Default properties declared directly in the class body:
class Animal {
kingdom = "Animalia";
constructor(name, species) { this.name = name; this.species = species; }
}
let dog = new Animal("Rex", "Dog");
console.log(dog.kingdom); // "Animalia"
Complete Example: Bank Account
class BankAccount {
#balance = 0;
#transactions = [];
constructor(owner, initialBalance = 0) {
this.owner = owner;
this.#balance = initialBalance;
}
deposit(amount) {
if (amount <= 0) throw new Error("Amount must be positive");
this.#balance += amount;
this.#transactions.push({ type: "deposit", amount });
return this;
}
withdraw(amount) {
if (amount <= 0) throw new Error("Amount must be positive");
if (amount > this.#balance) throw new Error("Insufficient funds");
this.#balance -= amount;
this.#transactions.push({ type: "withdrawal", amount });
return this;
}
getBalance() { return this.#balance; }
}
let account = new BankAccount("John", 1000);
account.deposit(500).withdraw(200);
console.log(account.getBalance()); // 1300
Remember: Private fields (#balance) can only be accessed inside the class.
Best Practices
- Use classes for related data — Group properties and methods
- Keep methods focused — One responsibility each
- Return
thisfor chaining — Enable fluent API
Common Mistakes
- Forgetting
new— Must usenewto create an instance - Using arrow functions as methods —
thiswon’t bind correctly - Not calling
super()— Required in child class constructors - Overcomplicating — Keep classes simple and focused