JavaScript Classes
Learn to create and use classes in JavaScript
🏗️ What are JavaScript Classes?
Classes are templates for creating objects. They encapsulate data and functions that work on that data. Think of a class as a blueprint for creating multiple similar objects.
// Simple class example
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
start() {
return `${this.brand} ${this.model} is starting!`;
}
}
// Create objects from the class
const myCar = new Car("Toyota", "Camry");
console.log(myCar.start());
Output:
Toyota Camry is starting!
Key Class Concepts
Constructor
Special method to initialize objects
constructor(name) {
this.name = name;
}
Methods
Functions inside a class
greet() {
return `Hello, ${this.name}!`;
}
Properties
Variables that store data
this.name = "John";
this.age = 25;
Instantiation
Creating objects from classes
const obj = new MyClass();
🔹 Basic Class Structure
Every class has a basic structure with constructor and methods:
class Person {
// Constructor - runs when object is created
constructor(name, age) {
this.name = name; // Property
this.age = age; // Property
}
// Method - function inside the class
introduce() {
return `Hi, I'm ${this.name} and I'm ${this.age} years old.`;
}
// Another method
haveBirthday() {
this.age++;
return `Happy birthday! Now I'm ${this.age}.`;
}
}
// Create an object (instance) from the class
const person1 = new Person("Alice", 25);
console.log(person1.introduce());
console.log(person1.haveBirthday());
Output:
Hi, I'm Alice and I'm 25 years old.
Happy birthday! Now I'm 26.
🔹 Real-World Example: Bank Account
Let's create a practical class for managing bank accounts:
class BankAccount {
constructor(accountHolder, initialBalance = 0) {
this.accountHolder = accountHolder;
this.balance = initialBalance;
this.transactions = [];
}
deposit(amount) {
if (amount > 0) {
this.balance += amount;
this.transactions.push(`Deposited $${amount}`);
return `Deposited $${amount}. New balance: $${this.balance}`;
}
return "Invalid deposit amount";
}
withdraw(amount) {
if (amount > 0 && amount <= this.balance) {
this.balance -= amount;
this.transactions.push(`Withdrew $${amount}`);
return `Withdrew $${amount}. New balance: $${this.balance}`;
}
return "Invalid withdrawal amount or insufficient funds";
}
getBalance() {
return `Account balance: $${this.balance}`;
}
getStatement() {
return {
holder: this.accountHolder,
balance: this.balance,
transactions: this.transactions
};
}
}
// Using the BankAccount class
const myAccount = new BankAccount("John Doe", 100);
console.log(myAccount.deposit(50));
console.log(myAccount.withdraw(30));
console.log(myAccount.getBalance());
Output:
Deposited $50. New balance: $150
Withdrew $30. New balance: $120
Account balance: $120
🔹 Class vs Object
Understanding the difference between classes and objects:
// Class = Blueprint/Template
class Dog {
constructor(name, breed) {
this.name = name;
this.breed = breed;
}
bark() {
return `${this.name} says Woof!`;
}
}
// Objects = Actual instances created from the class
const dog1 = new Dog("Buddy", "Golden Retriever");
const dog2 = new Dog("Max", "German Shepherd");
const dog3 = new Dog("Luna", "Husky");
// Each object has its own data but shares the same methods
console.log(dog1.bark()); // Buddy says Woof!
console.log(dog2.bark()); // Max says Woof!
console.log(dog3.bark()); // Luna says Woof!
// Objects are independent
console.log(dog1.name); // Buddy
console.log(dog2.breed); // German Shepherd
Output:
Buddy says Woof!
Max says Woof!
Luna says Woof!
Buddy
German Shepherd
🔹 Class Methods vs Functions
Methods are functions that belong to a class:
class Calculator {
constructor() {
this.result = 0;
}
// Method - belongs to the class
add(number) {
this.result += number;
return this; // Return 'this' for method chaining
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}
// Method chaining example
const calc = new Calculator();
const finalResult = calc.add(10).multiply(2).subtract(5).getResult();
console.log(finalResult); // 15
// Step by step
const calc2 = new Calculator();
calc2.add(5);
calc2.multiply(3);
console.log(calc2.getResult()); // 15
Output:
15
15